/**
 * 公共类
 * @type {*|exports|module.exports}
 */

var AV = require('leanengine');
var apis = require('../cloud/lib/apis');
var message = require('../cloud/lib/message');
var shopSellerNote = require('../cloud/shopSellerNote');
var moment = require('../cloud/common/moment');
var crypto = require('crypto');
var transliteration = require('transliteration');
var redisServer = require('../cloud/redis/redisServer');
var AV = require('leanengine');
var async = require("async");
// var qrcode = require( 'qrcode' );
var isFriend;
var isTribeMember;
var returnStr = null;
//实体类
var entityMap = {};
entityMap["Test"] = AV.Object.extend("Test");
entityMap["_File"] = AV.Object.extend("_File");
entityMap["_User"] = AV.Object.extend("_User");
entityMap["ConfigCounterFee"] = AV.Object.extend("ConfigCounterFee");
entityMap["Contacts"] = AV.Object.extend("Contacts");
entityMap["Dictionary"] = AV.Object.extend("Dictionary");
entityMap["Enjoy"] = AV.Object.extend("Enjoy");
entityMap["FriendRelation"] = AV.Object.extend("FriendRelation");
entityMap["Infocenter"] = AV.Object.extend("Infocenter");
entityMap["Media"] = AV.Object.extend("Media");
entityMap["Post"] = AV.Object.extend("Post");
entityMap["RecommendedFriends"] = AV.Object.extend("RecommendedFriends");
entityMap["RongyunLog"] = AV.Object.extend("RongyunLog");
entityMap["Shop_account"] = AV.Object.extend("Shop_account");
entityMap["Shop_account_bank"] = AV.Object.extend("Shop_account_bank");
entityMap["Shop_account_detail"] = AV.Object.extend("Shop_account_detail");
entityMap["Shop_account_verify"] = AV.Object.extend("Shop_account_verify");
entityMap["Shop_cart"] = AV.Object.extend("Shop_cart");
entityMap["Shop_common_pic"] = AV.Object.extend("Shop_common_pic");
entityMap["Shop_freight"] = AV.Object.extend("Shop_freight");
entityMap["Shop_good_fav"] = AV.Object.extend("Shop_good_fav");
entityMap["Shop_good_type"] = AV.Object.extend("Shop_good_type");
entityMap["Shop_goods"] = AV.Object.extend("Shop_goods");
entityMap["Shop_goods_model_stock"] = AV.Object.extend("Shop_goods_model_stock");
entityMap["Shop_goodsPic"] = AV.Object.extend("Shop_goodsPic");
entityMap["Shop_module_element"] = AV.Object.extend("Shop_module_element");
entityMap["Shop_notePic"] = AV.Object.extend("Shop_notePic");
entityMap["Shop_order"] = AV.Object.extend("Shop_order");
entityMap["Shop_order_goods"] = AV.Object.extend("Shop_order_goods");
entityMap["Shop_order_pay"] = AV.Object.extend("Shop_order_pay");
entityMap["Shop_order_refund"] = AV.Object.extend("Shop_order_refund");
entityMap["Shop_page_template"] = AV.Object.extend("Shop_page_template");
entityMap["Shop_receive_address"] = AV.Object.extend("Shop_receive_address");
entityMap["Shop_seller_note"] = AV.Object.extend("Shop_seller_note");
entityMap["Shop_shop"] = AV.Object.extend("Shop_shop");
entityMap["Shop_shop_fav"] = AV.Object.extend("Shop_shop_fav");
entityMap["Shop_shop_type"] = AV.Object.extend("Shop_shop_type");
entityMap["Shop_template_module"] = AV.Object.extend("Shop_template_module");
entityMap["Shop_tribe_goods"] = AV.Object.extend("Shop_tribe_goods");
entityMap["Thread"] = AV.Object.extend("Thread");
entityMap["Tribe"] = AV.Object.extend("Tribe");
entityMap["Tribe_share_goods"] = AV.Object.extend("Tribe_share_goods");
entityMap["Tribe_share_goods_pic"] = AV.Object.extend("Tribe_share_goods_pic");
entityMap["TribeLog"] = AV.Object.extend("TribeLog");
entityMap["TribeMember"] = AV.Object.extend("TribeMember");
entityMap["Version"] = AV.Object.extend("Version");
entityMap["Tribe_share_goods_pic"] = AV.Object.extend("Tribe_share_goods_pic");
entityMap["VetifyTribeMember"] = AV.Object.extend("VetifyTribeMember");
entityMap["Tribe_share_goods_enjoy"] = AV.Object.extend("Tribe_share_goods_enjoy");
entityMap["Post_share_goods"] = AV.Object.extend("Post_share_goods");
entityMap["Post_share_goods_pic"] = AV.Object.extend("Post_share_goods_pic");
entityMap["Enjoy_post_share_goods"] = AV.Object.extend("Enjoy_post_share_goods");
entityMap['SystemMessage'] = AV.Object.extend('SystemMessage');
entityMap['Shop_type'] = AV.Object.extend('Shop_type');
entityMap['Shop_type_good_relation'] = AV.Object.extend('Shop_type_good_relation');
entityMap['Shop_good_recommend'] = AV.Object.extend('Shop_good_recommend');
entityMap['Tribe_recommend'] = AV.Object.extend('Tribe_recommend');
entityMap['Tribe_order'] = AV.Object.extend('Tribe_order');
entityMap['Live_room'] = AV.Object.extend('Live_room');
entityMap['Live_Member'] = AV.Object.extend('Live_Member');
entityMap['Live_Notes'] = AV.Object.extend('Live_Notes');
entityMap['Live_remind'] = AV.Object.extend('Live_remind');
entityMap['LiveReport'] = AV.Object.extend('LiveReport');
entityMap['Live_order'] = AV.Object.extend('Live_order');
entityMap['Live_authority'] = AV.Object.extend('Live_authority');
entityMap['Tribe_score'] = AV.Object.extend('Tribe_score');
entityMap['Tribe_live'] = AV.Object.extend('Tribe_live');
entityMap['Brand_recommend'] = AV.Object.extend('Brand_recommend');
entityMap['Circle_message'] = AV.Object.extend('Circle_message');
entityMap['Circle_msg_source'] = AV.Object.extend('Circle_msg_source');
entityMap['Circle_msg_user_latest'] = AV.Object.extend('Circle_msg_user_latest');
entityMap['Circle_msg_reply'] = AV.Object.extend('Circle_msg_reply');
entityMap['Circle_msg_laud'] = AV.Object.extend('Circle_msg_laud');
entityMap['Thread_report'] = AV.Object.extend('Thread_report');
entityMap['Customization_apply'] = AV.Object.extend('Customization_apply');
entityMap['wx_group'] = AV.Object.extend('wx_group');
entityMap['Team_info'] = AV.Object.extend('Team_info');
entityMap['Team_role'] = AV.Object.extend('Team_role');
entityMap['Team_goods'] = AV.Object.extend('Team_goods');
entityMap['Team_member'] = AV.Object.extend('Team_member');
entityMap['Team_member_goods_info'] = AV.Object.extend('Team_member_goods_info');
entityMap['Team_goods_detail'] = AV.Object.extend('Team_goods_detail');
entityMap['Backstage_management'] = AV.Object.extend('Backstage_management');
entityMap['TribeLiveRelation_background'] = AV.Object.extend('TribeLiveRelation_background');
entityMap['Thread_background'] = AV.Object.extend('Thread_background');
entityMap['Allow_Create_Tribe'] = AV.Object.extend('Allow_Create_Tribe');
entityMap['User_shop'] = AV.Object.extend('User_shop');
entityMap['SynchronizationLiveTribe_background'] = AV.Object.extend('SynchronizationLiveTribe_background');
entityMap['Tribe_share_goods_background'] = AV.Object.extend('Tribe_share_goods_background');
entityMap['wx_group_type'] = AV.Object.extend('wx_group_type');
entityMap['Shop_master_slave'] = AV.Object.extend('Shop_master_slave');
entityMap['Fight_groups'] = AV.Object.extend('Fight_groups');
entityMap['Fight_groups_goods'] = AV.Object.extend('Fight_groups_goods');
entityMap['Fight_groups_order'] = AV.Object.extend('Fight_groups_order');
entityMap['userMerged'] = AV.Object.extend('userMerged');
exports.getEntity = getEntity;

function getEntity(key) {
  return entityMap[key];
}

exports.apiLimit = apiLimit;

function apiLimit(uId, actionName, cb) {
  var actionKey = {};
  actionKey["action"] = actionName;
  actionKey["user"] = uId;
  var interval = 0;//间隔次数
  var num = 0;//每日限制
  interval = apis["ApiLimit"][actionName + "Interval"];
  num = apis["ApiLimit"][actionName + "Num"];
  redisServer.getRedisContent(JSON.stringify(actionKey), function (err, result) {
    if (err != null) {
      var actionVal = {};
      actionKey["lastTime"] = new Date().getTime();
      actionKey["day"] = formatDateDay(new Date(), null);
      actionKey["count"] = 1;
      redisServer.addRedisContent(JSON.stringify(actionKey), actionVal, 60 * 60 * 24, function (err, result) {
      })
      return cb(1, null);
    } else {
      if (result == null || null == result.lastTime || undefined == result.lastTime) {
        var actionVal = {};
        actionVal["lastTime"] = new Date().getTime();
        actionVal["day"] = formatDateDay(new Date(), null);
        actionVal["count"] = 1;
        redisServer.addRedisContent(JSON.stringify(actionKey), actionVal, 60 * 60 * 24, function (err, result) {
        })
        return cb(1, null);
      } else {
        if (interval * 1000 < new Date().getTime() - result.lastTime) {
          //判断当天点击次数
          if (result.day != formatDateDay(new Date(), null)) {
            var actionVal = {};
            actionVal["lastTime"] = new Date().getTime();
            actionVal["day"] = formatDateDay(new Date(), null);
            actionVal["count"] = 1;
            redisServer.addRedisContent(JSON.stringify(actionKey), actionVal, 60 * 60 * 24, function (err, result) {
            })
            return cb(1, null);
          } else {
            if (result.count > num) {
              return cb(0, "当天访问此接口次数已受限，请明天再试！");
            } else {
              var actionVal = {};
              actionVal["lastTime"] = new Date().getTime();
              actionVal["day"] = formatDateDay(new Date(), null);
              actionVal["count"] = result.count + 1;
              redisServer.addRedisContent(JSON.stringify(actionKey), actionVal, 60 * 60 * 24, function (err, result) {
              })
              return cb(1, null);
            }
          }
        } else {
          return cb(0, "请勿频繁操作，请" + parseInt(interval + 1 - (new Date().getTime() - result.lastTime) / 1000) + "秒后再试！");
        }
      }
    }
  })
}

exports.formatParams = formatParams;

//如果为null或未定义则转为""并去所有空格
function formatParams(params) {
  var returnParam = "";
  if (params != null && params != undefined) {
    returnParam = params.toString().replace(/\s/g, "");
  }
  return returnParam;
}

/**
 * 去除字符串中所有空格
 */
String.prototype.TrimAll = function () {
  return this.replace(/\s/g, "");
}
/**
 * 去除字符串左右空格
 */
String.prototype.Trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.EscapeString = function () {
  // return  this.replace(/[\r\n\\\'\"\:]/g,"");
  return this.replace(/[\'\\\b\f\n\r\t]/g, "");
}

exports.commonTrim = function (str) {
  return str.Trim();
}
exports.addTitle = addTitle;

function addTitle(caption, type, width) {
  var title = {};
  title["caption"] = caption;
  title["type"] = type;
  title["width"] = width;
  return title;
}

exports.toPinyin = toPinyin;

function toPinyin(str) {
  returnStr = "";
  if (str == undefined || str == "" || str == null)
    return str;
  else {
    var reg = /^[A-Z]+$/;
    var tempStr = transliteration.slugify(str, {lowercase: false, separator: ""});
    var tempArry = tempStr.split("");
    for (var i = 0; i < tempArry.length; i++) {
      if (reg.test(tempArry[i]))
        returnStr += tempArry[i];
    }
    returnStr += " " + tempStr;
    return returnStr.toLowerCase();
  }
}

exports.initPage = initPage;

function initPage(page) {
  if (page == "" || page == null || page == undefined)
    page = "1";
  page = parseInt(page);
  if (isNaN(page))
    page = 1;
  if (page < 1)
    page = 1;
  return page;
}

/**
 * 验证是否登陆(黑名单用户直接注销出系统)
 */
exports.verifyLogin = function (request, response) {
  if (request.user == null) {
    return false;
  } else {
    if (request.user.get("status") == "0") {
      //修改用户sessionToken使其退出系统
      if (request.user.get("sessionToken") != "" && request.user.get("rcToken") != "" && request.user.get("sessionToken") != null && request.user.get("rcToken") != null) {
        getUserByOId(request.user.id, function (user) {
          if (user != null) {
            user.set("sessionToken", "");
            user.set("rcToken", "");
            user.save();
          }
          return false;
        });
      }
      return false;
    } else {
      return true;
    }
  }
}
/**
 * 判断当前用户是否存在于users中，存在则移除
 */
exports.verifyIsUsersArry = function (userOId, users) {
  var currUser = {};
  currUser["objectId"] = userOId;
  for (var i = 0; i < users.length; i++) {
    if (users[i].objectId == currUser.objectId) {
      users.splice(i, 1);
    }
  }
  return users;
}
/**
 * 判断是否是部落管理员
 */
exports.isTribeAdmin = function (tribeOId, userOId, callback) {
  var state = "0";
  if (tribeOId == "" || tribeOId == null || tribeOId == undefined || userOId == "" || userOId == null || userOId == undefined) {
    return callback(state);
  } else {
    var query = new AV.Query('TribeMember');
    query.equalTo("tribeOId", tribeOId);
    query.equalTo("userOId", userOId);
    query.first({
      success: function (object) {
        if (object != null) {
          if (object.get("userType") == "1" || object.get("userType") == "2") {
            state = "1";
          }
        }
        return callback(state);
      },
      error: function (error) {
        return callback(state);
      }
    });
  }
}
/**
 * 判断帖子媒体是否上传完毕
 */
exports.isTribeStatus = function (threadOId, type, callback) {
  var query = new AV.Query('Media');
  query.equalTo("threadOId", threadOId);

  query.equalTo("type", type);
  query.ascending("sortNum");
  query.find({
    success: function (objects) {
      var state = "1";
      if (objects != null) {
        for (var i = 0; i < objects.length; i++) {
          if (objects[i].get("status") != "1") {
            state = "0";
            break;
          }
        }
      }
      return callback(state, objects);
    },
    error: function (error) {
      return callback("0", null);
    }
  });
}

/**
 * 部落成员统计
 * @param tribeOId
 * @param callBack
 */
exports.tribeMemberCount = function (tribeOId, callback) {
  var queryTribeMember = new AV.Query('TribeMember');
  queryTribeMember.equalTo("tribeOId", tribeOId);
  queryTribeMember.containedIn("userType", ["1", "2", "3"]);
  queryTribeMember.count({
    success: function (count) {
      return callback(tribeOId, count);
    }, error: function (error) {
      return callback(tribeOId, 0);
    }
  })
}


/**
 * 查询普通部落成员信息 vsersion 2.5
 */
exports.tribeMemberInfoByCql = function (tribeOId, userOId, callback) {

  var cql = "select count(objectId),include userObj from TribeMember where userType in ('3') and tribeOId=? limit 3000"

  var query = AV.Query.doCloudQuery(cql, [tribeOId]).then(function (data) {
    var tribeMembers = data.results;
    var count = data.count;

    var userArry = [];
    var userObj = {};
    for (var i = 0; i < tribeMembers.length; i++) {
      userObj = getUserInfo(tribeMembers[i].get("userObj"));
      userObj["userType"] = tribeMembers[i].get("userType");
      userObj["isFriend"] = "0";
      userObj["noteName"] = "";
      userArry.push(userObj);
    }
    //查询我在部落中的角色
    var checkQueryTribeMember = new AV.Query('TribeMember');
    checkQueryTribeMember.equalTo("tribeOId", tribeOId);
    checkQueryTribeMember.equalTo("userOId", userOId);
    checkQueryTribeMember.first({
      success: function (userObj) {
        var userType = "-1";
        if (userObj != null) {
          userType = userObj.get("userType");
        }
        return callback(null, userArry, userType, count);
      }, error: function (err) {
        return callback(err.message, null, null, null);
      }
    });
  }, function (err) {
    return callback(err.message, null, null, null);
  })
}

/**
 * 查询部落成员信息
 */
exports.tribeMemberInfo = function (tribeOId, userOId, num, userType, callback) {

  var queryTribeMember = new AV.Query('TribeMember');
  queryTribeMember.equalTo("tribeOId", tribeOId);
  queryTribeMember.addDescending("sortNum");
  queryTribeMember.containedIn("userType", userType);
  queryTribeMember.include("userObj");
  queryTribeMember.limit(num);
  queryTribeMember.count({
    success: function (count) {
      queryTribeMember.find({
        success: function (tribeMembers) {
          var userArry = [];
          var userObj = {};
          for (var i = 0; i < tribeMembers.length; i++) {
            userObj = getUserInfo(tribeMembers[i].get("userObj"));
            userObj["userType"] = tribeMembers[i].get("userType");
            userObj["isFriend"] = "0";
            userObj["noteName"] = "";
            userArry.push(userObj);
          }
          //查询我在部落中的角色
          var checkQueryTribeMember = new AV.Query('TribeMember');
          checkQueryTribeMember.equalTo("tribeOId", tribeOId);
          checkQueryTribeMember.equalTo("userOId", userOId);
          checkQueryTribeMember.first({
            success: function (userObj) {
              var userType = "-1";
              if (userObj != null) {
                userType = userObj.get("userType");
              }
              return callback(null, userArry, userType, count);
            }, error: function (err) {
              return callback(err.message, null, null, null);
            }
          });
        }, error: function (err) {
          return callback(err.message, null, null, null);
        }
      });
    }, error: function (err) {
      return callback(err.message, null, null, null);
    }
  });
}


/**
 * 查询部落成员信息按最新加入时间   version 2.5  专业定制去掉黑名单与删除的
 */
exports.tribeMemberInfoByUpdateDesc = function (tribeOId, userOId, num, callback) {
  if (num == null || num == "" || num == undefined || num < 0)
    num = 1000;
  var queryTribeMember = new AV.Query('TribeMember');
  queryTribeMember.equalTo("tribeOId", tribeOId);
  queryTribeMember.addDescending("updatedAt");
  queryTribeMember.notContainedIn("userType", ["0", "-1"]);
  queryTribeMember.include("userObj");
  queryTribeMember.limit(num);


  queryTribeMember.count({
    success: function (count) {


      queryTribeMember.find({
        success: function (tribeMembers) {

          var userArry = [];
          var userObj = {};
          for (var i = 0; i < tribeMembers.length; i++) {
            userObj = getUserInfo(tribeMembers[i].get("userObj"));
            userObj["userType"] = tribeMembers[i].get("userType");
            userObj["isFriend"] = "0";
            userObj["noteName"] = "";
            userArry.push(userObj);
          }
          //查询我在部落中的角色
          var checkQueryTribeMember = new AV.Query('TribeMember');
          checkQueryTribeMember.equalTo("tribeOId", tribeOId);
          checkQueryTribeMember.equalTo("userOId", userOId);
          checkQueryTribeMember.first({
            success: function (userObj) {

              var userType = "-1";
              if (userObj != null) {
                userType = userObj.get("userType");
              }
              return callback(null, userArry, userType, count);
            }, error: function (err) {
              return callback(err.message, null, null, null);
            }
          });
        }, error: function (err) {
          return callback(err.message, null, null, null);
        }
      });
    }, error: function (err) {
      return callback(err.message, null, null, null);
    }
  });
}


/**
 * 查询部落成员信息(带分页)
 */
exports.tribeMemberInfoByPaging = function (searchVal, tribeOId, userOId, num, page, userType, callback) {
  var queryTribeMember = new AV.Query('TribeMember');
  if (searchVal != undefined && searchVal != "" && searchVal != null) {
    var queryUserName = new AV.Query('_User');
    queryUserName.limit(1000)
    queryUserName.contains("nickNameLowercase", searchVal);
    var queryUserUId = new AV.Query('_User');
    queryUserUId.equalTo("uid", searchVal);
    queryUserUId.limit(1000)
    var mainQuery = AV.Query.or(queryUserName, queryUserUId);
    queryTribeMember.matchesQuery("userObj", mainQuery);
  }
  queryTribeMember.equalTo("tribeOId", tribeOId);
  queryTribeMember.addAscending("sortNo");
  queryTribeMember.addAscending("createdAt");
  queryTribeMember.containedIn("userType", userType);
  queryTribeMember.include("userObj");
  queryTribeMember.limit(num);
  queryTribeMember.skip((page - 1) * num);
  queryTribeMember.count({
    success: function (count) {
      queryTribeMember.find({
        success: function (tribeMembers) {
          var userArry = [];
          var userObj = {};
          for (var i = 0; i < tribeMembers.length; i++) {
            userObj = getUserInfo(tribeMembers[i].get("userObj"));
            userObj["userType"] = tribeMembers[i].get("userType");
            userObj["isFriend"] = "0";
            userObj["noteName"] = "";
            userArry.push(userObj);
          }
          //查询我在部落中的角色
          var checkQueryTribeMember = new AV.Query('TribeMember');
          checkQueryTribeMember.equalTo("tribeOId", tribeOId);
          checkQueryTribeMember.equalTo("userOId", userOId);
          checkQueryTribeMember.first({
            success: function (userObj) {
              var userType = "-1";
              if (userObj != null) {
                userType = userObj.get("userType");
              }
              return callback(null, userArry, userType, count);
            }, error: function (err) {
              return callback(err.message, null, null, null);
            }
          });
        }, error: function (err) {
          return callback(err.message, null, null, null);
        }
      });
    }, error: function (err) {
      return callback(err.message, null, null, null);
    }
  });
}
/**
 * 查询部落管理员及创建人信息
 */
exports.tribeAdminInfo = function (tribeOId, callback) {
  if (tribeOId == null || tribeOId == "" || tribeOId == undefined) {
    return callback([]);
  }
  var queryTribeMember = new AV.Query('TribeMember');
  queryTribeMember.equalTo("tribeOId", tribeOId);
  queryTribeMember.containedIn("userType", ["1", "2"]);
  queryTribeMember.include("userObj");
  queryTribeMember.include("tribeObj");
  queryTribeMember.descending("createdAt");
  var jsonArrUser = [];
  var userObj = null;
  queryTribeMember.find({
    success: function (tribeMembers) {
      for (var i = 0; i < tribeMembers.length; i++) {
        userObj = getUserInfo(tribeMembers[i].get("userObj"));
        userObj["userType"] = tribeMembers[i].get("userType");
        userObj["tribeName"] = tribeMembers[i].get("tribeObj").get("name");
        jsonArrUser.push(userObj);
      }
      return callback(jsonArrUser);
    }, error: function (err) {
      return callback([]);
    }
  });
}
/**
 * 根据类型查询部落人数
 */
exports.findTribeMembersNumByType = function (tribeOId, type, callback) {
  if (tribeOId == "" || tribeOId == null || tribeOId == undefined) {
    return callback(0);
  }
  var query = new AV.Query('TribeMember');
  query.equalTo("tribeOId", tribeOId);
  if (type != "" && type != null && type != undefined)
    query.containedIn("userType", type);
  query.count({
    success: function (count) {
      return callback(count);
    },
    error: function (error) {
      return callback(0);
    }
  });
}
/**
 * 查询用户在部落中的类型
 */
exports.getTribeUserType = function (userOId, tribeOId, callback) {
  if (tribeOId == null || tribeOId == "" || tribeOId == undefined || userOId == null || userOId == "" || userOId == undefined) {
    return callback("错误的参数", null);
  } else {
    var query = new AV.Query('TribeMember');
    query.equalTo("tribeOId", tribeOId);
    query.equalTo("userOId", userOId);
    query.first({
      success: function (object) {
        var userType = "-1";
        if (object != null) {
          userType = object.get("userType");
        }
        return callback(null, userType);
      },
      error: function (error) {
        return callback(error.message, null);
      }
    });
  }
}
/**
 * 通用类，返回业务结果
 */
exports.getReturnArr = function (rState, rCode, rMsg, rResult) {
  returnStr = {};
  returnStr["state"] = rState;
  returnStr["code"] = rCode;
  returnStr["msg"] = rMsg;
  returnStr["result"] = rResult;
  return returnStr;
}
/**
 * 返回错误信息
 */
exports.getErrArr = function (errMsg) {
  returnStr = {};
  returnStr["state"] = "";
  returnStr["code"] = "10001";
  returnStr["msg"] = errMsg;
  returnStr["result"] = "";
  return returnStr;
}
exports.getOrderPayInfo = getOrderPayInfo;

function getOrderPayInfo(orderPay) {
  var orderPayObj = {};
  if (orderPay != null && orderPay != "" && orderPay != undefined) {
    if (orderPay.get("totalFee") != null && orderPay.get("totalFee") != "") {
      orderPayObj["totalFee"] = orderPay.get("totalFee");
    } else {
      orderPayObj["totalFee"] = 0;
    }
    if (orderPay.get("orderNo") != null && orderPay.get("orderNo") != "") {
      orderPayObj["orderNo"] = orderPay.get("orderNo");
    } else {
      orderPayObj["orderNo"] = "";
    }
    if (orderPay.get("payType") != null && orderPay.get("payType") != "") {
      orderPayObj["payType"] = orderPay.get("payType");
    } else {
      orderPayObj["payType"] = "";
    }
    if (orderPay.get("sellerNo") != null && orderPay.get("sellerNo") != "") {
      orderPayObj["sellerNo"] = orderPay.get("sellerNo");
    } else {
      orderPayObj["sellerNo"] = "";
    }
    if (orderPay.get("buyerNo") != null && orderPay.get("buyerNo") != "") {
      orderPayObj["buyerNo"] = orderPay.get("buyerNo");
    } else {
      orderPayObj["buyerNo"] = "";
    }
    if (orderPay.get("buyEmail") != null && orderPay.get("buyEmail") != "") {
      orderPayObj["buyEmail"] = orderPay.get("buyEmail");
    } else {
      orderPayObj["buyEmail"] = "";
    }
    if (orderPay.get("sellerEmail") != null && orderPay.get("sellerEmail") != "") {
      orderPayObj["sellerEmail"] = orderPay.get("sellerEmail");
    } else {
      orderPayObj["sellerEmail"] = "";
    }
    if (orderPay.get("tradeNo") != null && orderPay.get("tradeNo") != "") {
      orderPayObj["tradeNo"] = orderPay.get("tradeNo");
    } else {
      orderPayObj["tradeNo"] = "";
    }
    if (orderPay.createdAt != null) {
      orderPayObj["createdAt"] = formatDate(new Date(orderPay.createdAt.getTime()), null);
    } else {
      orderPayObj["createdAt"] = "";
    }
  }
  return orderPayObj;
}

/**
 * 封装模板模块资源信息
 */
exports.getElementInfo = getElementInfo;

function getElementInfo(pic) {
  var picObj = {};
  if (pic != null && pic != "" && pic != undefined) {
    if (pic.get("title") != null && pic.get("title") != "") {
      picObj["title"] = pic.get("title");
    } else {
      picObj["title"] = "";
    }
    if (pic.get("subtitle") != null && pic.get("subtitle") != "") {
      picObj["subtitle"] = pic.get("subtitle");
    } else {
      picObj["subtitle"] = "";
    }
    if (pic.get("content") != null && pic.get("content") != "") {
      picObj["content"] = pic.get("content");
    } else {
      picObj["content"] = "";
    }
    if (pic.get("description") != null && pic.get("description") != "") {
      picObj["description"] = pic.get("description");
    } else {
      picObj["description"] = "";
    }
    if (pic.get("sortNum") != null && pic.get("sortNum") != "") {
      picObj["sortNum"] = pic.get("sortNum");
    } else {
      picObj["sortNum"] = "";
    }
    if (pic.get("fatherSortNum") != null && pic.get("fatherSortNum") != "") {
      picObj["fatherSortNum"] = pic.get("fatherSortNum");
    } else {
      picObj["fatherSortNum"] = "";
    }
    if (pic.get("pic") != null && pic.get("pic") != "") {
      picObj["pic"] = pic.get("pic")._url;
      picObj["picId"] = pic.get("pic").id;
    } else {
      picObj["pic"] = "";
      picObj["picId"] = "";
    }
    if (pic.get("url") != null && pic.get("url") != "") {
      picObj["url"] = pic.get("url");
    } else {
      picObj["url"] = "";
    }
    if (pic.get("urlType") != null && pic.get("urlType") != "") {
      picObj["urlType"] = pic.get("urlType");
    } else {
      picObj["urlType"] = "";
    }
  }
  return picObj;
}

/**
 * 封装用户信息
 */
exports.getUserInfo = getUserInfo;
exports.getUserInfoNew = getUserInfoNew;
exports.getSearchUserInfo = getSearchUserInfo;

function getSearchUserInfo(user) {
  var userObj = {};
  if (user != null && user != undefined && user != "") {
    if (user.get("userAvatar") != null && user.get("userAvatar") != "") {
      userObj["userAvatar"] = user.get("userAvatar")._url;
//					+ "?imageView2/1/format/jpg";
      userObj["userAvatarId"] = user.get("userAvatar").id;
    } else {
      userObj["userAvatar"] = "";
      userObj["userAvatarId"] = "";
    }
    if (user.get("nickName") != null) {
      userObj["nickName"] = user.get("nickName");
    } else {
      userObj["nickName"] = "";
    }
    if (user.get("username") != null) {
      userObj["username"] = user.get("username");
    } else {
      userObj["username"] = "";
    }
    if (user.get("province") != null) {
      userObj["province"] = user.get("province");
    } else {
      userObj["province"] = "";
    }
    if (user.get("city") != null) {
      userObj["city"] = user.get("city");
    } else {
      userObj["city"] = "";
    }
    if (user.get("signature") != null) {
      userObj["signature"] = user.get("signature");
    } else {
      userObj["signature"] = "";
    }
    if (user.get("sex") != null) {
      userObj["sex"] = user.get("sex");
    } else {
      userObj["sex"] = "";
    }
    if (user.get("status") != null) {
      userObj["status"] = user.get("status");
    } else {
      userObj["status"] = "";
    }
    if (user.get("uid") != null) {
      userObj["familyId"] = user.get("uid");
    } else {
      userObj["familyId"] = "";
    }
    if (user.id != null) {
      userObj["objectId"] = user.id;
    } else {
      userObj["objectId"] = "";
    }
    if (user.createdAt != null) {
      userObj["createdAt"] = formatDate(new Date(user.createdAt.getTime()), null);
    } else {
      userObj["createdAt"] = "";
    }
    if (user.updatedAt != null) {
      userObj["updatedAt"] = user.updatedAt.getTime();
    } else {
      userObj["updatedAt"] = 0;
    }
  }
  return userObj;
}

/**
 * 封装用户进入部落请求信息
 */
exports.getVerifyTribeMember = getVerifyTribeMember;

function getVerifyTribeMember(obj) {
  var requestObj = {};
  if (obj != null && obj != undefined && obj != "") {
    if (obj.id != null) {
      requestObj["objectId"] = obj.id;
    } else {
      requestObj["objectId"] = "";
    }
    if (obj.get("content") != null) {
      requestObj["content"] = obj.get("content");
    } else {
      requestObj["content"] = apis['joinTribe']['content'];
    }
    if (obj.get("userObj") != null) {
      requestObj["userObj"] = getUserInfo(obj.get("userObj"));
    } else {
      requestObj["userObj"] = "";
    }
    if (obj.get("tribeOId") != null) {
      requestObj["tribeOId"] = obj.get("tribeOId");
    } else {
      requestObj["tribeOId"] = "";
    }
    if (obj.get("status") != null) {
      requestObj["status"] = obj.get("status");
    } else {
      requestObj["status"] = "";
    }
    if (obj.get("reason") != null) {
      requestObj["reason"] = obj.get("reason");
    } else {
      requestObj["reason"] = "";
    }
    if (obj.createdAt != null) {
      requestObj["createdAt"] = obj.createdAt.getTime();
    } else {
      requestObj["createdAt"] = 0;
    }
    if (obj.updatedAt != null) {
      requestObj["updatedAt"] = obj.updatedAt.getTime();
    } else {
      requestObj["updatedAt"] = 0;
    }
  }
  return requestObj;
}

exports.getPushUserInfo = getPushUserInfo;

function getPushUserInfo(user) {
  var userObj = {};
  if (user != null && user != undefined && user != "") {
    if (user.get("userAvatar") != null && user.get("userAvatar") != "") {
      userObj["userAvatar"] = user.get("userAvatar")._url;
//					+ "?imageView2/1/format/jpg";
      userObj["userAvatarId"] = user.get("userAvatar").id;
    } else {
      userObj["userAvatar"] = "";
      userObj["userAvatarId"] = "";
    }
    if (user.get("nickName") != null) {
      userObj["nickName"] = user.get("nickName");
    } else {
      userObj["nickName"] = "";
    }

    if (user.get("province") != null) {
      userObj["province"] = user.get("province");
    } else {
      userObj["province"] = "";
    }
    if (user.get("city") != null) {
      userObj["city"] = user.get("city");
    } else {
      userObj["city"] = "";
    }
    if (user.get("signature") != null) {
      userObj["signature"] = user.get("signature");
    } else {
      userObj["signature"] = "";
    }
    if (user.get("sex") != null) {
      userObj["sex"] = user.get("sex");
    } else {
      userObj["sex"] = "";
    }
    if (user.get("uid") != null) {
      userObj["familyId"] = user.get("uid");
    } else {
      userObj["familyId"] = "";
    }
    if (user.id != null) {
      userObj["objectId"] = user.id;
    } else {
      userObj["objectId"] = "";
    }
    if (user.createdAt != null) {
      userObj["createdAt"] = user.createdAt.getTime();
    } else {
      userObj["createdAt"] = 0;
    }
    if (user.updatedAt != null) {
      userObj["updatedAt"] = user.updatedAt.getTime();
    } else {
      userObj["updatedAt"] = 0;
    }
  }
  return userObj;
}

exports.getBaseUserInfo = getBaseUserInfo;

function getBaseUserInfo(user) {
  var userObj = {};
  if (user != null && user != undefined && user != "") {
    if (user.get("userAvatar") != null && user.get("userAvatar") != "") {
      userObj["userAvatar"] = user.get("userAvatar")._url;
//					+ "?imageView2/1/format/jpg";
      userObj["userAvatarId"] = user.get("userAvatar").id;
    } else {
      userObj["userAvatar"] = "";
      userObj["userAvatarId"] = "";
    }
    if (user.get("nickName") != null) {
      userObj["nickName"] = user.get("nickName");
    } else {
      userObj["nickName"] = "";
    }
    if (user.get("qrCode") != null && user.get("qrCode") != "") {
      userObj["qrCode"] = user.get("qrCode")._url;
      userObj["qrCodeId"] = user.get("qrCode").id;
    } else {
      userObj["qrCode"] = "";
      userObj["qrCodeId"] = "";
    }
    if (user.get("province") != null) {
      userObj["province"] = user.get("province");
    } else {
      userObj["province"] = "";
    }
    if (user.get("city") != null) {
      userObj["city"] = user.get("city");
    } else {
      userObj["city"] = "";
    }
    if (user.get("signature") != null) {
      userObj["signature"] = user.get("signature");
    } else {
      userObj["signature"] = "";
    }
    if (user.get("sex") != null) {
      userObj["sex"] = user.get("sex");
    } else {
      userObj["sex"] = "";
    }
    if (user.get("uid") != null) {
      userObj["familyId"] = user.get("uid");
    } else {
      userObj["familyId"] = "";
    }
    if (user.id != null) {
      userObj["objectId"] = user.id;
    } else {
      userObj["objectId"] = "";
    }
  }
  return userObj;
}

exports.getQrCodeFormat = getQrCodeFormat;

function getQrCodeFormat(user) {
  var nickName = "";
  if (user.get("nickName")) {
    nickName = new Buffer(user.get("nickName")).toString('base64');
  }
  if (!nickName) {
    nickName = "IA==";//空格
  }
  var returnFormat = "?imageMogr2/auto-orient/crop/!320x420"
  //returnFormat +="a50a0|watermark/2/text/"+nickName+"/font/5b6u6L2v6ZuF6buR/fontsize/450/fill/I0ZCNzI0NQ==/gravity/North/dx/10/dy/15|";
  //var tempStr = "执行力ID：";
  //if(user.get("uid")){
  //	tempStr+=user.get("uid");
  //}
  //returnFormat += "watermark/2/text/"+new Buffer(tempStr).toString('base64')+"/font/5b6u6L2v6ZuF6buR/fontsize/350/fill/I0ZCNzI0NQ==/gravity/North/dx/10/dy/50|";
  //returnFormat += "watermark/2/text/5omr5LiA5omr77yM5Yqg5oiR5Li65aW95Y-L/font/5b6u6L2v6ZuF6buR/fontsize/340/fill/IzhBODg4OA==/gravity/South/dx/10/dy/40";
  return returnFormat;
}

exports.getTribeSimple = getTribeSimple;

function getTribeSimple(tribe) {
  var tribeObj = {};
  if (tribe) {
    if (tribe.get('name')) {
      tribeObj['name'] = tribe.get('name');
    } else {
      tribeObj['name'] = '';
    }
    if (tribe.get('tribeAvator')) {
      tribeObj['tribeAvator'] = tribe.get('tribeAvator')._url;
    } else {
      tribeObj['tribeAvator'] = '';
    }
    if (tribe.id) {
      tribeObj['objectId'] = tribe.id;
    } else {
      tribeObj['objectId'] = '';
    }
  }
  return tribeObj;
}

function getUserInfo(user) {
  var userObj = {};
  if (user) {
    if (user.get("userAvatar")) {
      userObj["userAvatar"] = user.get("userAvatar")._url;
      userObj["userAvatarId"] = user.get("userAvatar").id;
    } else {
      userObj["userAvatar"] = "";
      userObj["userAvatarId"] = "";
    }
    if (user.get("nickName") != null) {
      userObj["nickName"] = user.get("nickName");
    } else {
      userObj["nickName"] = "";
    }
    if (user.get("qrCode") != null && user.get("qrCode") != "") {
      userObj["qrCode"] = user.get("qrCode")._url;
      userObj["qrCodeId"] = user.get("qrCode").id;
    } else {
      userObj["qrCode"] = "";
      userObj["qrCodeId"] = "";
    }
    if (user.get("province") != null) {
      userObj["province"] = user.get("province");
    } else {
      userObj["province"] = "";
    }
    if (user.get("city") != null) {
      userObj["city"] = user.get("city");
    } else {
      userObj["city"] = "";
    }
    if (user.get("signature") != null) {
      userObj["signature"] = user.get("signature");
    } else {
      userObj["signature"] = "";
    }
    if (user.get("sex") != null) {
      userObj["sex"] = user.get("sex");
    } else {
      userObj["sex"] = "";
    }
    if (user.get("uid") != null) {
      userObj["familyId"] = user.get("uid");
    } else {
      userObj["familyId"] = "";
    }
    if (user.id != null) {
      userObj["objectId"] = user.id;
    } else {
      userObj["objectId"] = "";
    }
    if (user.createdAt != null) {
      userObj["createdAt"] = user.createdAt.getTime();
    } else {
      userObj["createdAt"] = 0;
    }
    if (user.updatedAt != null) {
      userObj["updatedAt"] = user.updatedAt.getTime();
    } else {
      userObj["updatedAt"] = 0;
    }
    if (user.get("mobilePhoneNumber") != null) {
      userObj["mobilePhoneNumber"] = user.get("mobilePhoneNumber");
    } else {
      userObj["mobilePhoneNumber"] = "";
    }
  }
  return userObj;

}

function getUserInfoNew(user, callback) {
  var userObj = {};
  if (user) {
    if (user.get("userAvatar")) {
      userObj["userAvatar"] = user.get("userAvatar")._url;
      userObj["userAvatarId"] = user.get("userAvatar").id;
    } else {
      userObj["userAvatar"] = "";
      userObj["userAvatarId"] = "";
    }
    if (user.get("nickName") != null) {
      userObj["nickName"] = user.get("nickName");
    } else {
      userObj["nickName"] = "";
    }
    if (user.get("qrCode") != null && user.get("qrCode") != "") {
      userObj["qrCode"] = user.get("qrCode")._url;
      userObj["qrCodeId"] = user.get("qrCode").id;
    } else {
      userObj["qrCode"] = "";
      userObj["qrCodeId"] = "";
    }
    if (user.get("province") != null) {
      userObj["province"] = user.get("province");
    } else {
      userObj["province"] = "";
    }
    if (user.get("city") != null) {
      userObj["city"] = user.get("city");
    } else {
      userObj["city"] = "";
    }
    if (user.get("signature") != null) {
      userObj["signature"] = user.get("signature");
    } else {
      userObj["signature"] = "";
    }
    if (user.get("sex") != null) {
      userObj["sex"] = user.get("sex");
    } else {
      userObj["sex"] = "";
    }
    if (user.get("uid") != null) {
      userObj["familyId"] = user.get("uid");
    } else {
      userObj["familyId"] = "";
    }
    if (user.id != null) {
      userObj["objectId"] = user.id;
    } else {
      userObj["objectId"] = "";
    }
    if (user.createdAt != null) {
      userObj["createdAt"] = user.createdAt.getTime();
    } else {
      userObj["createdAt"] = 0;
    }
    if (user.updatedAt != null) {
      userObj["updatedAt"] = user.updatedAt.getTime();
    } else {
      userObj["updatedAt"] = 0;
    }
    if (user.get("mobilePhoneNumber") != null) {
      userObj["mobilePhoneNumber"] = user.get("mobilePhoneNumber");
    } else {
      userObj["mobilePhoneNumber"] = "";
    }
  }
  var query = new AV.Query('Backstage_management');
  var phone = userObj["mobilePhoneNumber"];
  if (phone == null || phone == undefined || phone == "") {
    userObj['backStage'] = '0';
    callback(userObj);
  } else {

    query.equalTo('userName', phone);
    query.find().then(function (personList) {

      if (personList.length > 0) {

        userObj['backStage'] = '1';

        callback(userObj);
      } else {

        userObj['backStage'] = '0';

        callback(userObj);
      }
    }, function (error) {

    });
  }


}

exports.getShopBaseInfo = getShopBaseInfo;

function getShopBaseInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != undefined && shop != "") {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("icon") != null && shop.get("icon") != "") {
      shopObj["icon"] = shop.get("icon")._url;
      shopObj["iconId"] = shop.get("icon").id;
    } else {
      shopObj["icon"] = "";
      shopObj["iconId"] = "";
    }
    if (shop.get("name") != null) {
      shopObj["name"] = shop.get("name");
    } else {
      shopObj["name"] = "";
    }
  }
  return shopObj;
}

exports.getShopWebInfo = getShopWebInfo;

function getShopWebInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != undefined && shop != "") {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("icon") != null && shop.get("icon") != "") {
      shopObj["icon"] = shop.get("icon")._url;
      shopObj["iconId"] = shop.get("icon").id;
    } else {
      shopObj["icon"] = "";
      shopObj["iconId"] = "";
    }
    if (shop.get("name") != null) {
      shopObj["name"] = shop.get("name");
    } else {
      shopObj["name"] = "";
    }
    if (shop.get("orderCancelCount") != null) {
      shopObj["orderCancelCount"] = shop.get("orderCancelCount");
    } else {
      shopObj["orderCancelCount"] = 0;
    }
    if (shop.get("orderNoPayCount") != null) {
      shopObj["orderNoPayCount"] = shop.get("orderNoPayCount");
    } else {
      shopObj["orderNoPayCount"] = 0;
    }
    if (shop.get("orderNoReceiveCount") != null) {
      shopObj["orderNoReceiveCount"] = shop.get("orderNoReceiveCount");
    } else {
      shopObj["orderNoReceiveCount"] = 0;
    }
    if (shop.get("orderNoSendCount") != null) {
      shopObj["orderNoSendCount"] = shop.get("orderNoSendCount");
    } else {
      shopObj["orderNoSendCount"] = 0;
    }
    if (shop.get("orderOkCount") != null) {
      shopObj["orderOkCount"] = shop.get("orderOkCount");
    } else {
      shopObj["orderOkCount"] = 0;
    }
    if (shop.get("orderRefundOkCount") != null) {
      shopObj["orderRefundOkCount"] = shop.get("orderRefundOkCount");
    } else {
      shopObj["orderRefundOkCount"] = 0;
    }
    if (shop.get("orderRefundingCount") != null) {
      shopObj["orderRefundingCount"] = shop.get("orderRefundingCount");
    } else {
      shopObj["orderRefundingCount"] = 0;
    }
    if (shop.get("orderRefundCount") != null) {
      shopObj["orderRefundCount"] = shop.get("orderRefundCount");
    } else {
      shopObj["orderRefundCount"] = 0;
    }
  }
  return shopObj;
}

exports.getShopInfo = getShopInfo;

function getShopInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != "" && shop != undefined) {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("icon") != null && shop.get("icon") != "") {
      shopObj["icon"] = shop.get("icon")._url;
      shopObj["iconId"] = shop.get("icon").id;
    } else {
      shopObj["icon"] = "";
      shopObj["iconId"] = "";
    }
    if (shop.get("qrCode") != null && shop.get("qrCode") != "") {
      shopObj["qrCode"] = shop.get("qrCode")._url;
      shopObj["qrCodeId"] = shop.get("qrCode").id;
    } else {
      shopObj["qrCode"] = "";
      shopObj["qrCodeId"] = "";
    }
    if (shop.get("picWidthxHeight") != null && shop.get("picWidthxHeight") != "") {
      shopObj["picWidthxHeight"] = shop.get("picWidthxHeight");
    } else {
      shopObj["picWidthxHeight"] = "";
    }
    if (shop.get("surfacePic") != null && shop.get("surfacePic") != "") {
      shopObj["surfacePic"] = shop.get("surfacePic")._url;
      shopObj["surfacePicId"] = shop.get("surfacePic").id;
    } else {
      shopObj["surfacePic"] = apis['qiniu']['url'] + "/" + apis['backgroud']['picName'];
      shopObj["surfacePicId"] = apis['backgroud']['id'];
    }
    if (shop.get("address") != null) {
      shopObj["address"] = shop.get("address");
    } else {
      shopObj["address"] = "";
    }
    if (shop.get("introduction") != null) {
      shopObj["introduction"] = shop.get("introduction");
    } else {
      shopObj["introduction"] = "";
    }

    if (shop.get("name") != null) {
      shopObj["name"] = shop.get("name");
    } else {
      shopObj["name"] = "";
    }
    if (shop.get("notice") != null) {
      shopObj["notice"] = shop.get("notice");
    } else {
      shopObj["notice"] = "";
    }
    if (shop.get("phone") != null) {
      shopObj["phone"] = shop.get("phone");
    } else {
      shopObj["phone"] = "";
    }
    if (shop.get("promote") != null) {
      shopObj["promote"] = shop.get("promote");
    } else {
      shopObj["promote"] = 0;
    }
    if (shop.get("sellNum") != null) {
      shopObj["sellNum"] = shop.get("sellNum");
    } else {
      shopObj["sellNum"] = 0;
    }
    if (shop.get("collectionNum") != null && shop.get("collectionNum") > 0) {
      shopObj["collectionNum"] = shop.get("collectionNum");
    } else {
      shopObj["collectionNum"] = 0;
    }
    if (shop.get("showType") != null) {
      shopObj["showType"] = shop.get("showType");
    } else {
      shopObj["showType"] = "";
    }
    if (shop.get("status") != null) {
      shopObj["status"] = shop.get("status");
    } else {
      shopObj["status"] = "";
    }
    if (shop.get("type") != null) {
      shopObj["type"] = shop.get("type");
    } else {
      shopObj["type"] = "";
    }
    if (shop.get("userOId") != null) {
      shopObj["userOId"] = shop.get("userOId");
    } else {
      shopObj["userOId"] = "";
    }
    if (shop.createdAt != null) {
      shopObj["createdAt"] = shop.createdAt.getTime();
    } else {
      shopObj["createdAt"] = 0;
    }
    if (shop.updatedAt != null) {
      shopObj["updatedAt"] = shop.updatedAt.getTime();
    } else {
      shopObj["updatedAt"] = 0;
    }
    if (shop.get("collectionNum") != null && shop.get("collectionNum") > 0) {
      shopObj["collectionNum"] = shop.get("collectionNum");
    } else {
      shopObj["collectionNum"] = 0;
    }
  }
  return shopObj;
}

exports.getShopTypeInfo = getShopTypeInfo;

/**
 * 封装店铺分类信息
 */
function getShopTypeInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != "" && shop != undefined) {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("name") != null) {
      shopObj["name"] = shop.get("name");
    } else {
      shopObj["name"] = "";
    }
    if (shop.get("sortNum") != null) {
      shopObj["sortNum"] = shop.get("sortNum");
    } else {
      shopObj["sortNum"] = 0;
    }
    if (shop.createdAt != null) {
      shopObj["createdTime"] = shop.createdAt.getTime();
    } else {
      shopObj["createdTime"] = 0;
    }
    if (shop.updatedAt != null) {
      shopObj["updatedTime"] = shop.updatedAt.getTime();
    } else {
      shopObj["updatedTime"] = 0;
    }
  }
  return shopObj;
}

exports.getBaseShopInfo = getBaseShopInfo;

/**
 * 封装基本店铺信息
 */
function getBaseShopInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != "" && shop != undefined) {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("icon") != null && shop.get("icon") != "") {
      shopObj["icon"] = shop.get("icon")._url;
      shopObj["iconId"] = shop.get("icon").id;
    } else {
      shopObj["icon"] = "";
      shopObj["iconId"] = "";
    }
    if (shop.get("name") != null) {
      shopObj["name"] = shop.get("name");
    } else {
      shopObj["name"] = "";
    }
    if (shop.get("introduction") != null) {
      shopObj["introduction"] = shop.get("introduction");
    } else {
      shopObj["introduction"] = "";
    }
    if (shop.get("surfacePic") != null && shop.get("surfacePic") != "") {
      shopObj["surfacePic"] = shop.get("surfacePic")._url;
      shopObj["surfacePicId"] = shop.get("surfacePic").id;
    } else {
      shopObj["surfacePic"] = apis['qiniu']['url'] + "/" + apis['backgroud']['picName'];
      shopObj["surfacePicId"] = apis['backgroud']['id'];
    }
    if (shop.get("showType") != null) {
      shopObj["showType"] = shop.get("showType");
    } else {
      shopObj["showType"] = "";
    }

  }
  return shopObj;
}

exports.getBaseSellerShopInfo = getBaseSellerShopInfo;

/**
 * 封装卖家基本店铺信息
 */
function getBaseSellerShopInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != "" && shop != undefined) {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("name") != null) {
      shopObj["name"] = shop.get("name");
    } else {
      shopObj["name"] = "";
    }
    if (shop.get("introduction") != null) {
      shopObj["introduction"] = shop.get("introduction");
    } else {
      shopObj["introduction"] = "";
    }
    if (shop.get("surfacePic") != null && shop.get("surfacePic") != "") {
      shopObj["surfacePic"] = shop.get("surfacePic")._url;
      shopObj["surfacePicId"] = shop.get("surfacePic").id;
    } else {
      shopObj["surfacePic"] = apis['qiniu']['url'] + "/" + apis['backgroud']['picName'];
      shopObj["surfacePicId"] = apis['backgroud']['id'];
    }
    if (shop.get("icon") != null && shop.get("icon") != "") {
      shopObj["icon"] = shop.get("icon")._url;
      shopObj["iconId"] = shop.get("icon").id;
    } else {
      shopObj["icon"] = "";
      shopObj["iconId"] = "";
    }
    if (shop.get("collectionNum") != null) {
      shopObj["collectionNum"] = shop.get("collectionNum");
    } else {
      shopObj["collectionNum"] = 0;
    }

    if (shop.get("userOId") != null) {
      shopObj["userOId"] = shop.get("userOId");
    } else {
      shopObj["userOId"] = "";
    }
  }
  return shopObj;
}

exports.getCartInfo = getCartInfo;

/**
 * 封装购物车信息
 */
function getCartInfo(shop) {
  var shopObj = {};
  if (shop != null && shop != "" && shop != undefined) {
    if (shop.id != null) {
      shopObj["objectId"] = shop.id;
    } else {
      shopObj["objectId"] = "";
    }
    if (shop.get("goodsOId") != null) {
      shopObj["goodsOId"] = shop.get("goodsOId");
    } else {
      shopObj["goodsOId"] = "";
    }
    if (shop.get("goodNo") != null) {
      shopObj["goodNo"] = shop.get("goodNo");
    } else {
      shopObj["goodNo"] = "";
    }
    if (shop.get("modelOId") != null) {
      shopObj["modelOId"] = shop.get("modelOId");
    } else {
      shopObj["modelOId"] = "";
    }
    if (shop.get("num") != null) {
      shopObj["num"] = shop.get("num");
    } else {
      shopObj["num"] = 0;
    }
//		if (shop.get("num") != null) {
//			shopObj["num"] = shop.get("num");
//		}else{
//			shopObj["num"]="";
//		}
    if (shop.get("promoter") != null) {
      shopObj["promoter"] = shop.get("promoter");
    } else {
      shopObj["promoter"] = "";
    }
    if (shop.get("userOId") != null) {
      shopObj["userOId"] = shop.get("userOId");
    } else {
      shopObj["userOId"] = "";
    }
    if (shop.get("tribeOId") != null) {
      shopObj["tribeOId"] = shop.get("tribeOId");
    } else {
      shopObj["tribeOId"] = "";
    }
    if (shop.get("tribe_share_goodsId") != null) {
      shopObj["tribe_share_goodsId"] = shop.get("tribe_share_goodsId");
    } else {
      shopObj["tribe_share_goodsId"] = "";
    }
    if (shop.get("isShare") != null) {
      shopObj["isShare"] = shop.get("isShare");
    } else {
      shopObj["isShare"] = "";
    }
  }
  return shopObj;
}

exports.getWebCartInfo = getWebCartInfo;

/**
 * 封装购物车信息(web)
 */
function getWebCartInfo(car) {
  var carObj = {};
  if (car != null && car != "" && car != undefined) {
    if (car.id != null) {
      carObj["objectId"] = car.id;
    } else {
      carObj["objectId"] = "";
    }
    if (car.get("goodsOId") != null) {
      carObj["goodsOId"] = car.get("goodsOId");
    } else {
      carObj["goodsOId"] = "";
    }
    if (car.get("goodNo") != null) {
      carObj["goodNo"] = car.get("goodNo");
    } else {
      carObj["goodNo"] = "";
    }
    if (car.get("modelOId") != null) {
      carObj["modelOId"] = car.get("modelOId");
    } else {
      carObj["modelOId"] = "";
    }
    if (car.get("num") != null) {
      carObj["num"] = car.get("num");
    } else {
      carObj["num"] = "";
    }
    if (car.get("num") != null) {
      carObj["num"] = car.get("num");
    } else {
      carObj["num"] = "";
    }
    if (car.get("promoter") != null) {
      carObj["promoter"] = car.get("promoter");
    } else {
      carObj["promoter"] = "";
    }
    if (car.get("userOId") != null) {
      carObj["userOId"] = car.get("userOId");
    } else {
      carObj["userOId"] = "";
    }
    if (car.get("tribeOId") != null) {
      carObj["tribeOId"] = car.get("tribeOId");
    } else {
      carObj["tribeOId"] = "";
    }
    if (car.get("distributor") != null) {
      carObj["distributor"] = car.get("distributor");
    } else {
      carObj["distributor"] = "";
    }
    if (car.get("userObj") != null) {
      carObj["userObj"] = getUserInfo(car.get("userObj"));
    } else {
      carObj["userObj"] = {};
    }
    if (car.get("goodsObj") != null) {
      carObj["goodsObj"] = getGoodsInfo(car.get("goodsObj"));
    } else {
      carObj["goodsObj"] = {};
    }
    if (car.get("modelObj") != null) {
      carObj["modelObj"] = getWebGoodsModel(car.get("modelObj"));
    } else {
      carObj["modelObj"] = {};
    }
  }
  return carObj;
}

exports.getOrderRefundObj = getOrderRefundObj;

function getOrderRefundObj(refundOrder) {
  var orderObj = {};
  if (refundOrder != null && refundOrder != "" && refundOrder != undefined) {
    if (refundOrder.id != null) {
      orderObj["objectId"] = refundOrder.id;
    } else {
      orderObj["objectId"] = "";
    }
    if (refundOrder.get("orderOId") != null) {
      orderObj["orderOId"] = refundOrder.get("orderOId");
    } else {
      orderObj["orderOId"] = "";
    }
    if (refundOrder.get("refundAnswer") != null) {
      orderObj["refundAnswer"] = refundOrder.get("refundAnswer");
    } else {
      orderObj["refundAnswer"] = "";
    }
    if (refundOrder.get("refundFee") != null) {
      orderObj["refundFee"] = formatMoneyFixed(refundOrder.get("refundFee"));
    } else {
      orderObj["refundFee"] = "";
    }
    if (refundOrder.get("refundReason") != null) {
      orderObj["refundReason"] = refundOrder.get("refundReason");
    } else {
      orderObj["refundReason"] = "";
    }
    if (refundOrder.get("refundReasonCode") != null) {
      orderObj["refundReasonCode"] = refundOrder.get("refundReasonCode");
      orderObj["refundReasonStr"] = apis["refundCode"][refundOrder.get("refundReasonCode")];
      if (orderObj["refundReasonCode"] == "6")
        orderObj["refundReasonStr"] = orderObj["refundReason"];
    } else {
      orderObj["refundReasonCode"] = "";
      orderObj["refundReasonStr"] = "";
    }
    if (refundOrder.get("refunder") != null) {
      orderObj["refunder"] = refundOrder.get("refunder");
    } else {
      orderObj["refunder"] = "";
    }
    if (refundOrder.get("type") != null) {
      orderObj["type"] = refundOrder.get("type");
    } else {
      orderObj["type"] = "";
    }
    if (refundOrder.get("title") != null) {
      orderObj["title"] = refundOrder.get("title");
    } else {
      orderObj["title"] = "";
    }
    if (refundOrder.get("refundObj") != null) {
      orderObj["user"] = getUserInfo(refundOrder.get("refundObj"));
    } else {
      orderObj["user"] = null;
    }
    orderObj["pics"] = [];
    if (refundOrder.get("picArray") != null) {
      for (var i = 0; i < refundOrder.get("picArray").length; i++) {
        if (refundOrder.get("picArray")[i] != null)
          orderObj["pics"].push(getShareGoodsPic(refundOrder.get("picArray")[i]));
      }
    }
    if (refundOrder.createdAt != null) {
      orderObj["createDate"] = refundOrder.createdAt.getTime();
    } else {
      orderObj["createDate"] = 0;
    }
  }
  return orderObj;
}

exports.getOrderWebInfo = getOrderWebInfo;

function getOrderWebInfo(order) {
  var orderObj = {};
  if (order != null && order != "" && order != undefined) {
    if (order.id != null) {
      orderObj["objectId"] = order.id;
    } else {
      orderObj["objectId"] = "";
    }
    if (order.get("shopOId") != null) {
      orderObj["shopOId"] = order.get("shopOId");
    } else {
      orderObj["shopOId"] = "";
    }
    if (order.get("sellerOId") != null) {
      orderObj["sellerOId"] = order.get("sellerOId");
    } else {
      orderObj["sellerOId"] = "";
    }
    if (order.get("shopObj") != null) {
      orderObj["shopObj"] = getShopInfo(order.get("shopObj"));
    } else {
      orderObj["shopObj"] = {};
    }
    if (order.get("sellerFee") != null) {
      orderObj["sellerFee"] = formatMoney(order.get("totalPrice") - order.get("fare") - order.get("promoterFee"));
    } else {
      orderObj["sellerFee"] = "0";
    }
    if (order.get("buyerOId") != null) {
      orderObj["buyerOId"] = order.get("buyerOId");
    } else {
      orderObj["buyerOId"] = "";
    }
    if (order.get("orderSendCount") != null) {
      orderObj["orderSendCount"] = order.get("orderSendCount");
    } else {
      orderObj["orderSendCount"] = 0;
    }
    if (order.get("totalPrice") != null) {
      orderObj["totalPrice"] = formatMoneyFixed(order.get("totalPrice"));
    } else {
      orderObj["totalPrice"] = "0";
    }
    if (order.get("promoterFee") != null) {
      orderObj["promoterFee"] = order.get("promoterFee");
    } else {
      orderObj["promoterFee"] = 0;
    }
    if (order.get("promote") != null) {
      orderObj["promote"] = order.get("promote");
    } else {
      orderObj["promote"] = 0;
    }
    if (order.get("fare") != null) {
      orderObj["fare"] = formatMoneyFixed(order.get("fare"));
    } else {
      orderObj["fare"] = "0";
    }
    if (order.get("payInfo") != null) {
      orderObj["payInfo"] = getOrderPayInfo(order.get("payInfo"));
    } else {
      orderObj["payInfo"] = "";
    }
    if (order.get("status") != null) {
      orderObj["status"] = order.get("status");
    } else {
      orderObj["status"] = "";
    }
    if (order.get("phone") != null) {
      orderObj["phone"] = order.get("phone");
    } else {
      orderObj["phone"] = "";
    }
    if (order.get("address") != null) {
      orderObj["address"] = order.get("address");
    } else {
      orderObj["address"] = "";
    }
    if (order.get("remark") != null) {
      orderObj["remark"] = order.get("remark");
    } else {
      orderObj["remark"] = "";
    }
    if (order.get("payTime") != null) {
      orderObj["payTime"] = formatDateNormal(order.get("payTime"), null);
      orderObj["payDate"] = order.get("payTime").getTime();
      orderObj["payDateNormal"] = formatDateNormal(order.get("payTime"), null);
    } else {
      orderObj["payDate"] = 0;
      orderObj["payDateNormal"] = "";
      orderObj["payTime"] = "";
    }
    if (order.get("payType") != null) {
      orderObj["payType"] = order.get("payType");
    } else {
      orderObj["payType"] = "";
    }
    if (order.get("ordeRemark") != null) {
      orderObj["ordeRemark"] = order.get("ordeRemark");
    } else {
      orderObj["ordeRemark"] = "";
    }
    if (order.get("goods") != null) {
      orderObj["goods"] = order.get("goods");
    } else {
      orderObj["goods"] = "";
    }
    if (order.get("deliverTime") != null) {
      orderObj["deliverTime"] = formatDateNormal(order.get("deliverTime"), null);
    } else {
      orderObj["deliverTime"] = "";
    }
    if (order.get("receiveTime") != null) {
      orderObj["receiveTime"] = formatDateNormal(order.get("receiveTime"), null);
    } else {
      orderObj["receiveTime"] = "";
    }
    if (order.get("expressCode") != null) {
      orderObj["expressCode"] = order.get("expressCode");
    } else {
      orderObj["expressCode"] = "";
    }
    if (order.get("logisticsCom") != null) {
      orderObj["logisticsCom"] = order.get("logisticsCom");
    } else {
      orderObj["logisticsCom"] = "";
    }
    if (order.get("logisticsComCode") != null) {
      orderObj["logisticsComCode"] = order.get("logisticsComCode");
      orderObj["logisticsComIcon"] = apis["logisticeIcon"][order.get("logisticsComCode")];
    } else {
      orderObj["logisticsComCode"] = "";
      orderObj["expressIcon"] = "";
    }
    if (order.get("refundStatus") != null) {
      orderObj["refundStatus"] = order.get("refundStatus");
    } else {
      orderObj["refundStatus"] = "";
    }

    if (order.get("receiver") != null) {
      orderObj["receiver"] = order.get("receiver");
    } else {
      orderObj["receiver"] = "";
    }
    if (order.get("orderCode") != null) {
      orderObj["orderCode"] = order.get("orderCode");
    } else {
      orderObj["orderCode"] = "";
    }
    if (order.get("status") != null) {
      orderObj["status"] = order.get("status");
      orderObj["statusVal"] = apis["orderStatusVal"][order.get("status").toString()];
      if (order.get("refundOkFee") != null && order.get("refundOkFee") != undefined && order.get("refundOkFee") != "") {
        orderObj["statusVal"] = orderObj["statusVal"] + "(有退款，退款" + order.get("refundOkFee") + "元)";
      }
    } else {
      orderObj["status"] = "";
      orderObj["statusVal"] = "未知状态";
    }
    if (order.createdAt != null) {
      orderObj["buyTime"] = formatDate(order.createdAt, null);
    } else {
      orderObj["buyTime"] = "";
    }
    if (order.createdAt != null) {
      orderObj["buyTimeNormal"] = formatDateNormal(order.createdAt, null);
    } else {
      orderObj["buyTimeNormal"] = "";
    }
    if (order.createdAt != null) {
      orderObj["buyDate"] = order.createdAt.getTime();
    } else {
      orderObj["buyDate"] = 0;
    }
    if (order.get("auditAccountContent") != null) {
      orderObj["auditAccountContent"] = order.get("auditAccountContent");
    } else {
      orderObj["auditAccountContent"] = "";
    }
    if (order.get("auditAccountStatus") != null) {
      orderObj["auditAccountStatus"] = order.get("auditAccountStatus");
    } else {
      orderObj["auditAccountStatus"] = "";
    }
    if (order.get("orderGoodsArray") != null) {
      var orderGoodsArray = [];
      var tempGoodsArray = order.get("orderGoodsArray");
      for (var i = 0; i < tempGoodsArray.length; i++) {
        if (tempGoodsArray[i] != null)
          orderGoodsArray.push(getOrderGoods(tempGoodsArray[i]));
      }
      orderObj["orderGoodsArray"] = orderGoodsArray;
    } else {
      orderObj["orderGoodsArray"] = [];
    }
    if (order.get("shopObj") != null) {
      orderObj["shopObj"] = getShopInfo(order.get("shopObj"));
    } else {
      orderObj["shopObj"] = {};
    }
  }
  return orderObj;
}

exports.getOrderWebInfoBak = getOrderWebInfoBak;

function getOrderWebInfoBak(order, cb) {
  var orderObj = {};
  if (order != null && order != "" && order != undefined) {
    if (order.id != null) {
      orderObj["objectId"] = order.id;
    } else {
      orderObj["objectId"] = "";
    }
    if (order.get("shopOId") != null) {
      orderObj["shopOId"] = order.get("shopOId");
    } else {
      orderObj["shopOId"] = "";
    }
    if (order.get("sellerOId") != null) {
      orderObj["sellerOId"] = order.get("sellerOId");
    } else {
      orderObj["sellerOId"] = "";
    }
    if (order.get("shopObj") != null) {
      orderObj["shopObj"] = getShopInfo(order.get("shopObj"));
    } else {
      orderObj["shopObj"] = {};
    }
    if (order.get("sellerFee") != null) {
      orderObj["sellerFee"] = formatMoney(order.get("totalPrice") - order.get("fare") - order.get("promoterFee"));
    } else {
      orderObj["sellerFee"] = "0";
    }
    if (order.get("buyerOId") != null) {
      orderObj["buyerOId"] = order.get("buyerOId");
    } else {
      orderObj["buyerOId"] = "";
    }
    if (order.get("orderSendCount") != null) {
      orderObj["orderSendCount"] = order.get("orderSendCount");
    } else {
      orderObj["orderSendCount"] = 0;
    }
    if (order.get("totalPrice") != null) {
      orderObj["totalPrice"] = formatMoneyFixed(order.get("totalPrice"));
    } else {
      orderObj["totalPrice"] = "0";
    }
    if (order.get("promoterFee") != null) {
      orderObj["promoterFee"] = order.get("promoterFee");
    } else {
      orderObj["promoterFee"] = 0;
    }
    if (order.get("promote") != null) {
      orderObj["promote"] = order.get("promote");
    } else {
      orderObj["promote"] = 0;
    }
    if (order.get("fare") != null) {
      orderObj["fare"] = formatMoneyFixed(order.get("fare"));
    } else {
      orderObj["fare"] = "0";
    }
    if (order.get("payInfo") != null) {
      orderObj["payInfo"] = getOrderPayInfo(order.get("payInfo"));
    } else {
      orderObj["payInfo"] = "";
    }
    if (order.get("status") != null) {
      orderObj["status"] = order.get("status");
    } else {
      orderObj["status"] = "";
    }
    if (order.get("phone") != null) {
      orderObj["phone"] = order.get("phone");
    } else {
      orderObj["phone"] = "";
    }
    if (order.get("address") != null) {
      orderObj["address"] = order.get("address");
    } else {
      orderObj["address"] = "";
    }
    if (order.get("remark") != null) {
      orderObj["remark"] = order.get("remark");
    } else {
      orderObj["remark"] = "";
    }
    if (order.get("payTime") != null) {
      orderObj["payTime"] = formatDateNormal(order.get("payTime"), null);
      orderObj["payDate"] = order.get("payTime").getTime();
      orderObj["payDateNormal"] = formatDateNormal(order.get("payTime"), null);
    } else {
      orderObj["payDate"] = 0;
      orderObj["payDateNormal"] = "";
      orderObj["payTime"] = "";
    }
    if (order.get("payType") != null) {
      orderObj["payType"] = order.get("payType");
    } else {
      orderObj["payType"] = "";
    }
    if (order.get("ordeRemark") != null) {
      orderObj["ordeRemark"] = order.get("ordeRemark");
    } else {
      orderObj["ordeRemark"] = "";
    }
    if (order.get("goods") != null) {
      orderObj["goods"] = order.get("goods");
    } else {
      orderObj["goods"] = "";
    }
    if (order.get("deliverTime") != null) {
      orderObj["deliverTime"] = formatDateNormal(order.get("deliverTime"), null);
    } else {
      orderObj["deliverTime"] = "";
    }
    if (order.get("receiveTime") != null) {
      orderObj["receiveTime"] = formatDateNormal(order.get("receiveTime"), null);
    } else {
      orderObj["receiveTime"] = "";
    }
    if (order.get("expressCode") != null) {
      orderObj["expressCode"] = order.get("expressCode");
    } else {
      orderObj["expressCode"] = "";
    }
    if (order.get("logisticsCom") != null) {
      orderObj["logisticsCom"] = order.get("logisticsCom");
    } else {
      orderObj["logisticsCom"] = "";
    }
    if (order.get("logisticsComCode") != null) {
      orderObj["logisticsComCode"] = order.get("logisticsComCode");
      orderObj["logisticsComIcon"] = apis["logisticeIcon"][order.get("logisticsComCode")];
    } else {
      orderObj["logisticsComCode"] = "";
      orderObj["expressIcon"] = "";
    }
    if (order.get("refundStatus") != null) {
      orderObj["refundStatus"] = order.get("refundStatus");
    } else {
      orderObj["refundStatus"] = "";
    }

    if (order.get("receiver") != null) {
      orderObj["receiver"] = order.get("receiver");
    } else {
      orderObj["receiver"] = "";
    }
    if (order.get("orderCode") != null) {
      orderObj["orderCode"] = order.get("orderCode");
    } else {
      orderObj["orderCode"] = "";
    }
    if (order.get("status") != null) {
      orderObj["status"] = order.get("status");
      orderObj["statusVal"] = apis["orderStatusVal"][order.get("status").toString()];
      if (order.get("refundOkFee") != null && order.get("refundOkFee") != undefined && order.get("refundOkFee") != "") {
        orderObj["statusVal"] = orderObj["statusVal"] + "(有退款，退款" + order.get("refundOkFee") + "元)";
      }
    } else {
      orderObj["status"] = "";
      orderObj["statusVal"] = "未知状态";
    }
    if (order.createdAt != null) {
      orderObj["buyTime"] = formatDate(order.createdAt, null);
    } else {
      orderObj["buyTime"] = "";
    }
    if (order.createdAt != null) {
      orderObj["buyTimeNormal"] = formatDateNormal(order.createdAt, null);
    } else {
      orderObj["buyTimeNormal"] = "";
    }
    if (order.createdAt != null) {
      orderObj["buyDate"] = order.createdAt.getTime();
    } else {
      orderObj["buyDate"] = 0;
    }
    if (order.get("auditAccountContent") != null) {
      orderObj["auditAccountContent"] = order.get("auditAccountContent");
    } else {
      orderObj["auditAccountContent"] = "";
    }
    if (order.get("auditAccountStatus") != null) {
      orderObj["auditAccountStatus"] = order.get("auditAccountStatus");
    } else {
      orderObj["auditAccountStatus"] = "";
    }


    if (order.get("shopObj") != null) {
      orderObj["shopObj"] = getShopInfo(order.get("shopObj"));
    } else {
      orderObj["shopObj"] = {};
    }


    if (order.get("orderGoodsArray") != null) {

      var orderGoodsArray = [];
      var tempGoodsArray = order.get("orderGoodsArray");


      async.eachSeries(tempGoodsArray, function (good, cb1) {
        getOrderGoodsBak(good, function (orderGood) {


          orderGoodsArray.push(orderGood);
          cb1();
        })
      }, function (end) {
        orderObj["orderGoodsArray"] = orderGoodsArray;
        cb(orderObj);
      })
    } else {
      cb(orderObj);
    }
  } else {
    cb(orderObj);
  }
}

/**
 * 封装订单信息
 * @param shop
 * @returns {___anonymous20550_20551}
 */
exports.getOrderInfo = getOrderInfo;

function getOrderInfo(order) {
  var orderObj = {};
  if (order != null && order != "" && order != undefined) {
    if (order.id != null) {
      orderObj["objectId"] = order.id;
    } else {
      orderObj["objectId"] = "";
    }
    if (order.get("shopOId") != null) {
      orderObj["shopOId"] = order.get("shopOId");
    } else {
      orderObj["shopOId"] = "";
    }
    if (order.get("sellerOId") != null) {
      orderObj["sellerOId"] = order.get("sellerOId");
    } else {
      orderObj["sellerOId"] = "";
    }
    if (order.get("buyerOId") != null) {
      orderObj["buyerOId"] = order.get("buyerOId");
    } else {
      orderObj["buyerOId"] = "";
    }
    if (order.get("payInfo") != null) {
      orderObj["payInfo"] = getOrderPayInfo(order.get("payInfo"));
    } else {
      orderObj["payInfo"] = {};
    }
    if (order.get("totalPrice") != null) {
      orderObj["totalPrice"] = formatMoneyFixed(order.get("totalPrice"));
    } else {
      orderObj["totalPrice"] = "0";
    }
    if (order.get("promoterFee") != null) {
      orderObj["promoterFee"] = order.get("promoterFee");
    } else {
      orderObj["promoterFee"] = 0;
    }
    if (order.get("fare") != null) {
      orderObj["fare"] = formatMoneyFixed(order.get("fare"));
    } else {
      orderObj["fare"] = "";
    }
    if (order.get("discount") != null) {
      orderObj["discount"] = order.get("discount").toString();
    } else {
      orderObj["discount"] = "";
    }
    if (order.get("status") != null) {
      orderObj["status"] = order.get("status");
      orderObj["statusVal"] = apis["orderStatusVal"][order.get("status").toString()];
      if (order.get("refundOkFee") != null && order.get("refundOkFee") != undefined && order.get("refundOkFee") != "") {
        orderObj["statusVal"] = orderObj["statusVal"] + "(有退款，退款" + order.get("refundOkFee") + "元)";
      }
    } else {
      orderObj["status"] = "";
      orderObj["statusVal"] = "未知状态";
    }
    if (order.get("phone") != null) {
      orderObj["phone"] = order.get("phone");
    } else {
      orderObj["phone"] = "";
    }
    if (order.get("address") != null) {
      orderObj["address"] = order.get("address");
    } else {
      orderObj["address"] = "";
    }
    if (order.get("remark") != null) {
      orderObj["remark"] = order.get("remark");
    } else {
      orderObj["remark"] = "";
    }
    if (order.get("orderSendCount") != null) {
      orderObj["orderSendCount"] = order.get("orderSendCount");
    } else {
      orderObj["orderSendCount"] = 0;
    }
    if (order.get("payTime") != null) {
      orderObj["payTime"] = order.get("payTime").getTime();
    } else {
      orderObj["payTime"] = 0;
    }
    if (order.get("orderRefundObj") != null && order.get("orderRefundObj") != "" && order.get("orderRefundObj") != undefined) {
      if (order.get("orderRefundObj").createdAt != undefined)
        orderObj["refundTime"] = order.get("orderRefundObj").createdAt.getTime();
      else
        orderObj["refundTime"] = 0;
    } else {
      orderObj["refundTime"] = 0;
    }
    if (order.get("ordeRemark") != null) {
      orderObj["ordeRemark"] = order.get("ordeRemark");
    } else {
      orderObj["ordeRemark"] = "";
    }
    if (order.get("deliverTime") != null) {
      orderObj["deliverTime"] = order.get("deliverTime").getTime();
    } else {
      if (order.get("orderRefundObj") != null && order.get("orderRefundObj") != "" && order.get("orderRefundObj") != undefined) {
        if (order.get("orderRefundObj").createdAt != undefined)
          orderObj["deliverTime"] = order.get("orderRefundObj").createdAt.getTime();
        else
          orderObj["deliverTime"] = 0;
      } else {
        orderObj["deliverTime"] = 0;
      }
    }
    if (order.get("receiveTime") != null) {
      orderObj["receiveTime"] = order.get("receiveTime").getTime();
    } else {
      if (order.get("orderRefundObj") != null && order.get("orderRefundObj") != "" && order.get("orderRefundObj") != undefined) {
        if (order.get("orderRefundObj").createdAt != null && order.get("orderRefundObj").createdAt != undefined)
          orderObj["receiveTime"] = order.get("orderRefundObj").createdAt.getTime();
        else
          orderObj["receiveTime"] = 0;
      } else {
        orderObj["receiveTime"] = 0;
      }
    }
    if (order.get("expressCode") != null) {
      orderObj["expressCode"] = order.get("expressCode");
    } else {
      orderObj["expressCode"] = "";
    }
    if (order.get("logisticsCom") != null) {
      orderObj["logisticsCom"] = order.get("logisticsCom");
    } else {
      orderObj["logisticsCom"] = "";
    }
    if (order.get("logisticsComCode") != null) {
      orderObj["logisticsComCode"] = order.get("logisticsComCode");
    } else {
      orderObj["logisticsComCode"] = "";
    }
    if (order.get("receiver") != null) {
      orderObj["receiver"] = order.get("receiver");
    } else {
      orderObj["receiver"] = "";
    }
    if (order.get("orderCode") != null) {
      orderObj["orderCode"] = order.get("orderCode");
    } else {
      orderObj["orderCode"] = "";
    }
    if (order.get("fightGroupOId") != null) {
      orderObj["fightGroupOId"] = order.get("fightGroupOId");
    } else {
      orderObj["fightGroupOId"] = "";
    }
    if (order.createdAt != null) {
      orderObj["buyTime"] = order.createdAt.getTime();
    } else {
      orderObj["buyTime"] = 0;
    }
    if (order.get("taskTime") != null && order.get("taskTime") != "") {
      orderObj["autoReceiveTime"] = order.get("taskTime").getTime();
    } else {
      orderObj["autoReceiveTime"] = 0;
    }
    if (order.get("task") != null) {
      orderObj["autoType"] = order.get("task");
    } else {
      orderObj["autoType"] = "";
    }
    if (order.get("goods") != null) {
      orderObj["goods"] = order.get("goods");
    } else {
      orderObj["goods"] = [];
    }
    if (order.get("orderGoodsArray") != null) {
      var orderGoodsArray = [];
      var tempGoodsArray = order.get("orderGoodsArray");
      for (var i = 0; i < tempGoodsArray.length; i++) {
        if (tempGoodsArray[i] != null)
          orderGoodsArray.push(getOrderGoods(tempGoodsArray[i]));
      }
      orderObj["orderGoodsArray"] = orderGoodsArray;
    } else {
      orderObj["orderGoodsArray"] = [];
    }
  }
  return orderObj;
}


exports.getOrderInfoBak = getOrderInfoBak;

function getOrderInfoBak(order, cb) {
  var orderObj = {};
  if (order != null && order != "" && order != undefined) {
    if (order.id != null) {
      orderObj["objectId"] = order.id;
    } else {
      orderObj["objectId"] = "";
    }
    if (order.get("shopOId") != null) {
      orderObj["shopOId"] = order.get("shopOId");
    } else {
      orderObj["shopOId"] = "";
    }
    if (order.get("sellerOId") != null) {
      orderObj["sellerOId"] = order.get("sellerOId");
    } else {
      orderObj["sellerOId"] = "";
    }
    if (order.get("buyerOId") != null) {
      orderObj["buyerOId"] = order.get("buyerOId");
    } else {
      orderObj["buyerOId"] = "";
    }
    if (order.get("payInfo") != null) {
      orderObj["payInfo"] = getOrderPayInfo(order.get("payInfo"));
    } else {
      orderObj["payInfo"] = {};
    }
    if (order.get("totalPrice") != null) {
      orderObj["totalPrice"] = formatMoneyFixed(order.get("totalPrice"));
    } else {
      orderObj["totalPrice"] = "0";
    }
    if (order.get("promoterFee") != null) {
      orderObj["promoterFee"] = order.get("promoterFee");
    } else {
      orderObj["promoterFee"] = 0;
    }
    if (order.get("fare") != null) {
      orderObj["fare"] = formatMoneyFixed(order.get("fare"));
    } else {
      orderObj["fare"] = "";
    }
    if (order.get("discount") != null) {
      orderObj["discount"] = order.get("discount").toString();
    } else {
      orderObj["discount"] = "";
    }
    if (order.get("status") != null) {
      orderObj["status"] = order.get("status");
      orderObj["statusVal"] = apis["orderStatusVal"][order.get("status").toString()];
      if (order.get("refundOkFee") != null && order.get("refundOkFee") != undefined && order.get("refundOkFee") != "") {
        orderObj["statusVal"] = orderObj["statusVal"] + "(有退款，退款" + order.get("refundOkFee") + "元)";
      }
    } else {
      orderObj["status"] = "";
      orderObj["statusVal"] = "未知状态";
    }
    if (order.get("phone") != null) {
      orderObj["phone"] = order.get("phone");
    } else {
      orderObj["phone"] = "";
    }
    if (order.get("address") != null) {
      orderObj["address"] = order.get("address");
    } else {
      orderObj["address"] = "";
    }
    if (order.get("remark") != null) {
      orderObj["remark"] = order.get("remark");
    } else {
      orderObj["remark"] = "";
    }
    if (order.get("orderSendCount") != null) {
      orderObj["orderSendCount"] = order.get("orderSendCount");
    } else {
      orderObj["orderSendCount"] = 0;
    }
    if (order.get("payTime") != null) {
      orderObj["payTime"] = order.get("payTime").getTime();
    } else {
      orderObj["payTime"] = 0;
    }
    if (order.get("orderRefundObj") != null && order.get("orderRefundObj") != "" && order.get("orderRefundObj") != undefined) {
      if (order.get("orderRefundObj").createdAt != undefined)
        orderObj["refundTime"] = order.get("orderRefundObj").createdAt.getTime();
      else
        orderObj["refundTime"] = 0;
    } else {
      orderObj["refundTime"] = 0;
    }
    if (order.get("ordeRemark") != null) {
      orderObj["ordeRemark"] = order.get("ordeRemark");
    } else {
      orderObj["ordeRemark"] = "";
    }
    if (order.get("deliverTime") != null) {
      orderObj["deliverTime"] = order.get("deliverTime").getTime();
    } else {
      if (order.get("orderRefundObj") != null && order.get("orderRefundObj") != "" && order.get("orderRefundObj") != undefined) {
        if (order.get("orderRefundObj").createdAt != undefined)
          orderObj["deliverTime"] = order.get("orderRefundObj").createdAt.getTime();
        else
          orderObj["deliverTime"] = 0;
      } else {
        orderObj["deliverTime"] = 0;
      }
    }
    if (order.get("receiveTime") != null) {
      orderObj["receiveTime"] = order.get("receiveTime").getTime();
    } else {
      if (order.get("orderRefundObj") != null && order.get("orderRefundObj") != "" && order.get("orderRefundObj") != undefined) {
        if (order.get("orderRefundObj").createdAt != null && order.get("orderRefundObj").createdAt != undefined)
          orderObj["receiveTime"] = order.get("orderRefundObj").createdAt.getTime();
        else
          orderObj["receiveTime"] = 0;
      } else {
        orderObj["receiveTime"] = 0;
      }
    }
    if (order.get("expressCode") != null) {
      orderObj["expressCode"] = order.get("expressCode");
    } else {
      orderObj["expressCode"] = "";
    }
    if (order.get("logisticsCom") != null) {
      orderObj["logisticsCom"] = order.get("logisticsCom");
    } else {
      orderObj["logisticsCom"] = "";
    }
    if (order.get("logisticsComCode") != null) {
      orderObj["logisticsComCode"] = order.get("logisticsComCode");
    } else {
      orderObj["logisticsComCode"] = "";
    }
    if (order.get("receiver") != null) {
      orderObj["receiver"] = order.get("receiver");
    } else {
      orderObj["receiver"] = "";
    }
    if (order.get("orderCode") != null) {
      orderObj["orderCode"] = order.get("orderCode");
    } else {
      orderObj["orderCode"] = "";
    }
    if (order.createdAt != null) {
      orderObj["buyTime"] = order.createdAt.getTime();
    } else {
      orderObj["buyTime"] = 0;
    }
    if (order.get("taskTime") != null && order.get("taskTime") != "") {
      orderObj["autoReceiveTime"] = order.get("taskTime").getTime();
    } else {
      orderObj["autoReceiveTime"] = 0;
    }
    if (order.get("task") != null) {
      orderObj["autoType"] = order.get("task");
    } else {
      orderObj["autoType"] = "";
    }
    if (order.get("goods") != null) {
      orderObj["goods"] = order.get("goods");
    } else {
      orderObj["goods"] = [];
    }
    if (order.get("orderGoodsArray") != null) {

      var orderGoodsArray = [];
      var tempGoodsArray = order.get("orderGoodsArray");


      async.eachSeries(tempGoodsArray, function (good, cb1) {
        getOrderGoodsBak(good, function (orderGood) {


          orderGoodsArray.push(orderGood);
          cb1();
        })
      }, function (end) {
        orderObj["orderGoodsArray"] = orderGoodsArray;
        cb(orderObj);
      })
    } else {
      cb(orderObj);
    }
  } else
    cb(orderObj);
}


/**
 * 封装商品订单信息
 * @param order
 * @returns {___anonymous22802_22803}
 */
exports.getOrderGoods = getOrderGoods;

function getOrderGoods(orderGoods) {
  var orderGoodsObj = {};
  if (orderGoods != null && orderGoods != "" && orderGoods != undefined) {
    if (orderGoods.id != null) {
      orderGoodsObj["objectId"] = orderGoods.id;
    } else {
      orderGoodsObj["objectId"] = "";
    }
    if (orderGoods.get("goodsModel") != null) {
      orderGoodsObj["goodsModel"] = orderGoods.get("goodsModel");
    } else {
      orderGoodsObj["goodsModel"] = "";
    }
    if (orderGoods.get("num") != null) {
      orderGoodsObj["num"] = orderGoods.get("num");
    } else {
      orderGoodsObj["num"] = "";
    }
    if (orderGoods.get("goodsOId") != null) {
      orderGoodsObj["goodsOId"] = orderGoods.get("goodsOId");
    } else {
      orderGoodsObj["goodsOId"] = "";
    }
    if (orderGoods.get("goodsName") != null) {
      orderGoodsObj["goodsName"] = orderGoods.get("goodsName");
    } else {
      orderGoodsObj["goodsName"] = "";
    }
    if (orderGoods.get("price") != null) {
      orderGoodsObj["price"] = formatMoneyFixed(orderGoods.get("price"));
    } else {
      orderGoodsObj["price"] = "0";
    }
    if (orderGoods.get("goodsPicURL") != null) {
      orderGoodsObj["goodsPicURL"] = orderGoods.get("goodsPicURL");
    } else {
      orderGoodsObj["goodsPicURL"] = "";
    }
    if (orderGoods.get("goodsPicId") != null) {
      orderGoodsObj["goodsPicId"] = orderGoods.get("goodsPicId");
    } else {
      orderGoodsObj["goodsPicId"] = "";
    }
    if (orderGoods.get("orderOId") != null) {
      orderGoodsObj["orderOId"] = orderGoods.get("orderOId");
    } else {
      orderGoodsObj["orderOId"] = "";
    }

    if (orderGoods.get("promote") != null) {
      orderGoodsObj["promote"] = orderGoods.get("promote");
    } else {
      orderGoodsObj["promote"] = 0;
    }
    if (orderGoods.get("promoter") != null) {
      orderGoodsObj["promoter"] = orderGoods.get("promoter");
    } else {
      orderGoodsObj["promoter"] = 0;
    }
    if (orderGoods.get("promoterFee") != null) {
      orderGoodsObj["promoterFee"] = orderGoods.get("promoterFee");
    } else {
      orderGoodsObj["promoterFee"] = 0;
    }
    if (orderGoods.get("sellerFee") != null) {
      orderGoodsObj["sellerFee"] = orderGoods.get("sellerFee");
    } else {
      orderGoodsObj["sellerFee"] = 0;
    }
  }
  return orderGoodsObj;
}

exports.getOrderGoodsBak = getOrderGoodsBak;

function getOrderGoodsBak(orderGoods, cb) {
  var orderGoodsObj = {};
  if (orderGoods != null && orderGoods != "" && orderGoods != undefined) {
    if (orderGoods.id != null) {
      orderGoodsObj["objectId"] = orderGoods.id;
    } else {
      orderGoodsObj["objectId"] = "";
    }
    if (orderGoods.get("goodsModel") != null) {
      orderGoodsObj["goodsModel"] = orderGoods.get("goodsModel");
    } else {
      orderGoodsObj["goodsModel"] = "";
    }
    if (orderGoods.get("num") != null) {
      orderGoodsObj["num"] = orderGoods.get("num");
    } else {
      orderGoodsObj["num"] = "";
    }
    if (orderGoods.get("goodsOId") != null) {
      orderGoodsObj["goodsOId"] = orderGoods.get("goodsOId");
    } else {
      orderGoodsObj["goodsOId"] = "";
    }
    if (orderGoods.get("goodsName") != null) {
      orderGoodsObj["goodsName"] = orderGoods.get("goodsName");
    } else {
      orderGoodsObj["goodsName"] = "";
    }
    if (orderGoods.get("price") != null) {
      orderGoodsObj["price"] = formatMoneyFixed(orderGoods.get("price"));
    } else {
      orderGoodsObj["price"] = "0";
    }
    if (orderGoods.get("goodsPicURL") != null) {
      orderGoodsObj["goodsPicURL"] = orderGoods.get("goodsPicURL");
    } else {
      orderGoodsObj["goodsPicURL"] = "";
    }
    if (orderGoods.get("goodsPicId") != null) {
      orderGoodsObj["goodsPicId"] = orderGoods.get("goodsPicId");
    } else {
      orderGoodsObj["goodsPicId"] = "";
    }
    if (orderGoods.get("orderOId") != null) {
      orderGoodsObj["orderOId"] = orderGoods.get("orderOId");
    } else {
      orderGoodsObj["orderOId"] = "";
    }

    if (orderGoods.get("promote") != null) {
      orderGoodsObj["promote"] = orderGoods.get("promote");
    } else {
      orderGoodsObj["promote"] = 0;
    }
    if (orderGoods.get("promoter") != null) {
      orderGoodsObj["promoter"] = orderGoods.get("promoter");
    } else {
      orderGoodsObj["promoter"] = "";
    }
    if (orderGoods.get("promoterFee") != null) {
      orderGoodsObj["promoterFee"] = orderGoods.get("promoterFee");
    } else {
      orderGoodsObj["promoterFee"] = 0;
    }
    if (orderGoods.get("writerFee") != null) {
      orderGoodsObj["writerFee"] = orderGoods.get("writerFee");
    } else {
      orderGoodsObj["writerFee"] = 0;
    }
    if (orderGoods.get("distributionFee") != null) {
      orderGoodsObj["distributionFee"] = orderGoods.get("distributionFee");
    } else {
      orderGoodsObj["distributionFee"] = 0;
    }
    if (orderGoods.get("sellerFee") != null) {
      orderGoodsObj["sellerFee"] = orderGoods.get("sellerFee");
    } else {
      orderGoodsObj["sellerFee"] = 0;
    }
    var userQuery = new AV.Query("_User");
    userQuery.equalTo("objectId", orderGoods.get("distributor") ? orderGoods.get("distributor") : "");
    userQuery.first().then(function (user) {

      var distributor = {};

      if (user) {
        orderGoodsObj["distributorName"] = user.get("nickName")
        distributor["objectId"] = user.id;
        distributor["name"] = user.get("nickName");


        distributor["fee"] = orderGoods.get("distributionFee") ? orderGoods.get("distributionFee") : 0;

      } else {
        distributor["objectId"] = "";
        distributor["name"] = "";
        distributor["fee"] = 0;
      }

      orderGoodsObj["distributor"] = distributor;


      var userQuery = new AV.Query("_User");
      userQuery.equalTo("objectId", orderGoods.get("promoter") ? orderGoods.get("promoter") : "");
      userQuery.first().then(function (user) {
        var promoter = {};
        if (user) {
          orderGoodsObj["promoterName"] = user.get("nickName")
          promoter["objectId"] = user.id;
          promoter["name"] = user.get("nickName");
          promoter["fee"] = orderGoods.get("promoterFee") ? orderGoods.get("promoterFee") : 0;

        } else {
          promoter["objectId"] = "";
          promoter["name"] = "";
          promoter["fee"] = 0;
        }

        orderGoodsObj["promoterObj"] = promoter;


        var userQuery = new AV.Query("_User");
        userQuery.equalTo("objectId", orderGoods.get("writer") ? orderGoods.get("writer") : "");
        userQuery.first().then(function (user) {
          var writer = {};

          if (user) {
            orderGoodsObj["writerName"] = user.get("nickName")
            writer["objectId"] = user.id;
            writer["name"] = user.get("nickName");
            writer["fee"] = orderGoods.get("writerFee") ? orderGoods.get("writerFee") : 0;

          } else {
            writer["objectId"] = "";
            writer["name"] = "";
            writer["fee"] = 0;
          }

          orderGoodsObj["writer"] = writer;

          var userQuery = new AV.Query("Tribe");
          userQuery.equalTo("objectId", orderGoods.get("tribeOId") ? orderGoods.get("tribeOId") : "");
          userQuery.first().then(function (tribe) {

            var tribeObj = {};

            if (tribe) {
              orderGoodsObj["tribeName"] = tribe.get("name");
              tribeObj["objectId"] = tribe.id;
              tribeObj["name"] = tribe.get("name");

            } else {
              tribeObj["objectId"] = "";
              tribeObj["name"] = "";
            }

            orderGoodsObj["tribe"] = tribeObj;


            cb(orderGoodsObj);

          }, function (err) {
            cb(orderGoodsObj);

          })

        }, function (err) {
          cb(orderGoodsObj);

        })


      }, function (err) {
        cb(orderGoodsObj);

      })


    }, function (err) {
      cb(orderGoodsObj);

    })


  } else {
    cb(orderGoodsObj);
  }
}

/**
 * 封装店长笔记信息
 */
exports.getSellerNote = getSellerNote;

function getSellerNote(noteInfo) {
  var noteObj = {};
  if (noteInfo != null && noteInfo != "" && noteInfo != undefined) {
    if (noteInfo.id != null) {
      noteObj["objectId"] = noteInfo.id;
    } else {
      noteObj["objectId"] = "";
    }
    if (noteInfo.get("title") != null) {
      noteObj["title"] = noteInfo.get("title");
    } else {
      noteObj["title"] = "";
    }
    if (noteInfo.get("content") != null) {
      noteObj["content"] = noteInfo.get("content");
    } else {
      noteObj["content"] = "";
    }
    if (noteInfo.get("shopOId") != null) {
      noteObj["shopOId"] = noteInfo.get("shopOId");
    } else {
      noteObj["shopOId"] = "";
    }
    if (noteInfo.get("picName") != null) {
      noteObj["picName"] = noteInfo.get("picName");
    } else {
      noteObj["picName"] = "";
    }
    if (noteInfo.createdAt != null) {
      noteObj["createdAt"] = noteInfo.createdAt.getTime();
    } else {
      noteObj["createdAt"] = 0;
    }
    if (noteInfo.updatedAt != null) {
      noteObj["updatedDate"] = formatDateNormal(noteInfo.updatedAt, null);
    } else {
      noteObj["updatedDate"] = "";
    }
    if (noteInfo.updatedAt != null) {
      noteObj["updatedAt"] = noteInfo.updatedAt.getTime();
    } else {
      noteObj["updatedAt"] = 0;
    }
  }
  return noteObj;
}

/**
 * 封装部落分享赚钱商品
 */
exports.getShareGoods = getShareGoods;

function getShareGoods(shareGoods) {
  var Obj = {};
  if (shareGoods != null && shareGoods != "" && shareGoods != undefined) {

    if (shareGoods.id != null) {
      Obj["objectId"] = shareGoods.id;
    } else {
      Obj["objectId"] = "";
    }
    if (shareGoods.get("title") != null) {
      Obj["title"] = shareGoods.get("title");
    } else {
      Obj["title"] = "";
    }
    if (shareGoods.get("content") != null) {
      Obj["content"] = shareGoods.get("content");
    } else {
      Obj["content"] = "";
    }
    if (shareGoods.get("tribeOId") != null) {
      Obj["tribeOId"] = shareGoods.get("tribeOId");
    } else {
      Obj["tribeOId"] = "";
    }
    if (shareGoods.get("picName") != null && shareGoods.get("picName") != "" && shareGoods.get("picName") != undefined) {
      if (shareGoods.get("picName").indexOf("http://") == -1)
        Obj["picURL"] = apis['qiniu']['url'] + "/" + shareGoods.get("picName");
      else
        Obj["picURL"] = shareGoods.get("picName");
    } else {
      Obj["picURL"] = "";
    }
    if (shareGoods.createdAt != null) {
      Obj["createdAt"] = shareGoods.createdAt.getTime();
    } else {
      Obj["createdAt"] = 0;
    }
    if (shareGoods.updatedAt != null) {
      Obj["updatedDate"] = formatDateNormal(shareGoods.updatedAt, null);
    } else {
      Obj["updatedDate"] = "";
    }
    if (shareGoods.updatedAt != null) {
      Obj["updatedAt"] = shareGoods.updatedAt.getTime();
    } else {
      Obj["updatedAt"] = 0;
    }
    if (shareGoods.get("hotNum") != null) {
      Obj["hotNum"] = shareGoods.get("hotNum");
    } else {
      Obj["hotNum"] = 0;
    }
    if (shareGoods.get("enjoyNum") != null) {
      Obj["enjoyNum"] = shareGoods.get("enjoyNum");
    } else {
      Obj["enjoyNum"] = 0;
    }
    if (shareGoods.get("userOId") != null) {
      Obj["userOId"] = shareGoods.get("userOId");
    } else {
      Obj["userOId"] = 0;
    }
    // if(shareGoods.get("isTop")!=null){
    // 	Obj["isTop"]=shareGoods.get("isTop");
    // }else{
    // 	Obj["isTop"]=false;
    // }
    Obj.isCanShare = shareGoods.get("isCanShare")
    //查询赞的数量
    return Obj;
    // var enjoyQuery = new AV.Query('Tribe_share_goods_enjoy');
    // enjoyQuery.equalTo("tribeShareGoodsOId", shareGoods.id);
    // enjoyQuery.count().then(function (count) {
    //     Obj["enjoyNum"] = count;
    // },function (err) {
    //     Obj["enjoyNum"] = 0;
    // })
  }
  // return Obj;
}

/**
 * 封装基本部落分享赚钱商品
 */
exports.getBaseShareGoods = getBaseShareGoods;

function getBaseShareGoods(shareGoods) {
  var Obj = {};
  if (shareGoods != null && shareGoods != "" && shareGoods != undefined) {
    if (shareGoods.id != null) {
      Obj["objectId"] = shareGoods.id;
    } else {
      Obj["objectId"] = "";
    }
    if (shareGoods.get("title") != null) {
      Obj["title"] = shareGoods.get("title");
    } else {
      Obj["title"] = "";
    }
    if (shareGoods.get("content") != null) {
      Obj["content"] = shareGoods.get("content");
    } else {
      Obj["content"] = "";
    }
    if (shareGoods.get("picName") != null) {
      Obj["picURL"] = apis['qiniu']['url'] + "/" + shareGoods.get("picName");
    } else {
      Obj["picURL"] = "";
    }
    if (shareGoods.createdAt != null) {
      Obj["createdAt"] = shareGoods.createdAt.getTime();
    } else {
      Obj["createdAt"] = 0;
    }
    if (shareGoods.updatedAt != null) {
      Obj["updatedDate"] = formatDateNormal(shareGoods.updatedAt, null);
    } else {
      Obj["updatedDate"] = "";
    }
    if (shareGoods.updatedAt != null) {
      Obj["updatedAt"] = shareGoods.updatedAt.getTime();
    } else {
      Obj["updatedAt"] = 0;
    }
    if (shareGoods.get("tribeGoodsObj").get("distributionFee") != null && shareGoods.get("tribeGoodsObj").get("distributionFee") != "")
      Obj["distributionFee"] = shareGoods.get("tribeGoodsObj").get("distributionFee");
    else {
      Obj["distributionFee"] = 0;
    }
    if (shareGoods.get("tribeGoodsObj").get("distributionRatio") != null && shareGoods.get("tribeGoodsObj").get("distributionRatio") != "")
      Obj["distributionRatio"] = shareGoods.get("tribeGoodsObj").get("distributionRatio");
    else {
      Obj["distributionRatio"] = 0;
    }

  }
  return Obj;
}

/**
 * 封装分享赚钱笔记图片信息
 */
exports.getShareGoodsPic = getShareGoodsPic;

function getShareGoodsPic(picInfo) {
  var picObj = {};
  if (picInfo != null && picInfo != "" && picInfo != undefined) {
    if (picInfo.id != null) {
      picObj["picId"] = picInfo.id;
    } else {
      picObj["picId"] = "";
    }
    if (picInfo.get("picName") != null && picInfo.get("picName") != "" && picInfo.get("picName") != undefined) {
      picObj["picURL"] = apis['qiniu']['url'] + "/" + picInfo.get("picName");
    } else {
      picObj["picURL"] = "";
    }
    if (picInfo.get("picName") != null) {
      picObj["picName"] = picInfo.get("picName");
    } else {
      picObj["picName"] = "";
    }
    if (picInfo.get("sortNum") != null) {
      picObj["sortNum"] = picInfo.get("sortNum");
    } else {
      picObj["sortNum"] = "";
    }
    if (picInfo.get("picWidthxHeight") != null && picInfo.get("picWidthxHeight") != "") {
      picObj["picWidthxHeight"] = picInfo.get("picWidthxHeight");
    } else {
      picObj["picWidthxHeight"] = "1x1";
    }
  }
  return picObj;
}

/**
 * 封装店长笔记信息(网页)
 */
exports.getWebSellerNote = getWebSellerNote;

function getWebSellerNote(noteInfo) {
  var noteObj = {};
  if (noteInfo != null && noteInfo != "" && noteInfo != undefined) {
    if (noteInfo.id != null) {
      noteObj["objectId"] = noteInfo.id;
    } else {
      noteObj["objectId"] = "";
    }
    if (noteInfo.get("title") != null) {
      noteObj["title"] = noteInfo.get("title");
    } else {
      noteObj["title"] = "";
    }
    if (noteInfo.get("content") != null) {
      noteObj["content"] = noteInfo.get("content");
    } else {
      noteObj["content"] = "";
    }
    if (noteInfo.get("shopOId") != null) {
      noteObj["shopOId"] = noteInfo.get("shopOId");
    } else {
      noteObj["shopOId"] = "";
    }
    if (noteInfo.get("shopObj") != null) {
      noteObj["shopObj"] = getShopInfo(noteInfo.get("shopObj"));
    } else {
      noteObj["shopObj"] = "";
    }
    if (noteInfo.get("userOId") != null) {
      noteObj["userOId"] = noteInfo.get("userOId");
    } else {
      noteObj["userOId"] = "";
    }
    if (noteInfo.get("userObj") != null) {
      noteObj["userObj"] = getUserInfo(noteInfo.get("userObj"));
    } else {
      noteObj["userObj"] = "";
    }
    if (noteInfo.get("picName") != null) {
      noteObj["picName"] = noteInfo.get("picName");
    } else {
      noteObj["picName"] = "";
    }
    if (noteInfo.get("picArray") != null) {
      noteObj["picArray"] = noteInfo.get("picArray");
    } else {
      noteObj["picName"] = new Array;
    }
    if (noteInfo.createdAt != null) {
      noteObj["createdAt"] = noteInfo.createdAt.getTime();
    } else {
      noteObj["createdAt"] = 0;
    }
    if (noteInfo.updatedAt != null) {
      noteObj["updatedDate"] = formatDateNormal(noteInfo.updatedAt, null);
    } else {
      noteObj["updatedDate"] = "";
    }
    if (noteInfo.updatedAt != null) {
      noteObj["updatedYear"] = noteInfo.updatedAt.getFullYear();

    } else {
      noteObj["updatedYear"] = 0;
    }
    if (noteInfo.updatedAt != null) {
      var month = "0" + (noteInfo.updatedAt.getMonth() + 1);
      month = month.substring(month.length - 2);

      noteObj["updatedMonth"] = month;
    } else {
      noteObj["updatedMonth"] = "";
    }
    if (noteInfo.updatedAt != null) {
      var day = "0" + noteInfo.updatedAt.getDate();
      day = day.substring(day.length - 2);
      noteObj["updatedDay"] = day;
    } else {
      noteObj["updatedDay"] = "";
    }
    if (noteInfo.updatedAt != null) {
      noteObj["updatedAt"] = noteInfo.updatedAt.getTime();
    } else {
      noteObj["updatedAt"] = "";
    }
  }
  return noteObj;
}

/**
 * 封装店长笔记图片信息
 */
exports.getNotePic = getNotePic;

function getNotePic(picInfo) {
  var picObj = {};
  if (picInfo != null && picInfo != "" && picInfo != undefined) {
    if (picInfo.id != null) {
      picObj["picId"] = picInfo.id;
    } else {
      picObj["picId"] = "";
    }
    if (picInfo.get("picName") != null) {
      picObj["picURL"] = apis['qiniu']['url'] + "/" + picInfo.get("picName");
    } else {
      picObj["picURL"] = "";
    }
    if (picInfo.get("picName") != null) {
      picObj["picName"] = picInfo.get("picName");
    } else {
      picObj["picName"] = "";
    }
    if (picInfo.get("sortNum") != null) {
      picObj["sortNum"] = picInfo.get("sortNum");
    } else {
      picObj["sortNum"] = "";
    }
    if (picInfo.get("picWidthxHeight") != null && picInfo.get("picWidthxHeight") != "") {
      picObj["picWidthxHeight"] = picInfo.get("picWidthxHeight");
    } else {
      picObj["picWidthxHeight"] = "1x1";
    }
  }
  return picObj;
}

/**
 * 封装帖子信息
 */
exports.getThreadInfo = getThreadInfo;

function getThreadInfo(thread) {
  var threadObj = {};

  if (thread != null && thread != "" && thread != undefined) {
    if (thread.id != null) {
      threadObj["objectId"] = thread.id;
    } else {
      threadObj["objectId"] = "";
    }
    if (thread.get("isTop") != null) {
      threadObj["isTop"] = thread.get("isTop");
    } else {
      threadObj["isTop"] = "0";
    }
    if (thread.get("status") != null) {
      threadObj["status"] = thread.get("status");
    } else {
      threadObj["status"] = 0;
    }
    if (thread.get("content") != null) {
      threadObj["content"] = thread.get("content");
    } else {
      threadObj["content"] = "";
    }

    if (thread.get("createrObj") != null) {
      threadObj["author"] = getUserInfo(thread.get("createrObj"));
    } else {
      threadObj["author"] = {};
    }
    if (thread.get("shareThreadStatus") != null) {
      threadObj["shareThreadStatus"] = thread.get("shareThreadStatus");
    } else {
      threadObj["shareThreadStatus"] = 1;
    }
    if (thread.get("fromThread") != null) {
      threadObj["fromThread"] = thread.get("fromThread");
    } else {
      threadObj["fromThread"] = "";
    }
    if (thread.get("fromTribe") != null) {
      threadObj["fromTribe"] = {"objectId": thread.get("fromTribe")};
    } else {
      threadObj["fromTribe"] = {};
    }
    if (thread.get("isShare") != null) {
      threadObj["isCanShare"] = thread.get("isShare");
    } else {
      threadObj["isCanShare"] = "1";
    }
    if (thread.get("fromCreater") != null) {
      threadObj["fromCreater"] = getUserInfo(thread.get("fromCreaterObj"));
    } else {
      threadObj["fromCreater"] = {};
    }
    if (thread.get("tribeOId") != null) {
      threadObj["tribeOId"] = thread.get("tribeOId");
    } else {
      threadObj["tribeOId"] = "";
    }
    if (thread.get("postNum") != null) {
      threadObj["postNum"] = thread.get("postNum");
    } else {
      threadObj["postNum"] = 0;
    }
    if (thread.get("shareNum") != null) {
      threadObj["shareNum"] = thread.get("shareNum");
    } else {
      threadObj["shareNum"] = 0;
    }
    if (thread.createdAt != null) {
      threadObj["createdAt"] = thread.createdAt.getTime();
    } else {
      threadObj["createdAt"] = 0;
    }
    if (thread.updatedAt != null) {
      threadObj["updatedAt"] = thread.updatedAt.getTime();
    } else {
      threadObj["updatedAt"] = 0;
    }

    if (thread.get("enjoyNum") != null) {
      threadObj["enjoyNum"] = thread.get("enjoyNum");

    } else {
      threadObj["enjoyNum"] = 0;
    }

    if (thread.get("streamId") != null) {
      threadObj["streamId"] = thread.get("streamId");

    } else {
      threadObj["streamId"] = "";
    }

    if (thread.get("startTime") != null) {
      threadObj["startTime"] = thread.get("startTime");

    } else {
      threadObj["startTime"] = 0;
    }

    if (thread.get("sortTime") != null) {
      threadObj["sortDate"] = thread.get("sortTime");

    } else {
      threadObj["timer"] = 0;
    }

    if (thread.get("playTime") != null) {
      threadObj["playTime"] = thread.get("playTime");

    } else {
      threadObj["playTime"] = 0;
    }
    if (thread.get("isTiming") != null) {
      threadObj["timer"] = thread.get("isTiming");

    } else {
      threadObj["timer"] = 0;
    }

    if (thread.get("streambackup") != null && thread.get("streambackup") != "") {
      threadObj["streambackup"] = apis['qiniu']['live_cdn'] + thread.get("streambackup");

    } else {
      threadObj["streambackup"] = "";
    }
    if (thread.get("videoUrl") != null) {
      threadObj["videoUrl"] = apis['qiniu']['live_cdn'] + thread.get("videoUrl");

    } else {
      threadObj["videoUrl"] = "";
    }

    threadObj["pic"] = [];
    threadObj["picB"] = [];
    threadObj["audio"] = [];
    threadObj["media"] = [];
    threadObj["goods"] = [];
    if (thread.get("picArray") != "" && thread.get("picArray") != null && thread.get("picArray") != undefined) {
      for (var i = 0; i < thread.get("picArray").length; i++) {
        threadObj["pic"].push(getMediaInfo(thread.get("picArray")[i]));
      }
    }
    if (thread.get("goods") != "" && thread.get("goods") != null && thread.get("goods") != undefined) {
      for (var i = 0; i < thread.get("goods").length; i++) {
        threadObj["goods"].push(getGoodsInfo(thread.get("goods")[i]));
      }
    }
    if (thread.get("picArrayB") != "" && thread.get("picArrayB") != null && thread.get("picArrayB") != undefined) {
      for (var i = 0; i < thread.get("picArrayB").length; i++) {
        threadObj["picB"].push(getMediaInfo(thread.get("picArrayB")[i]));
      }
    }
    if (thread.get("audioArray") != "" && thread.get("audioArray") != null && thread.get("audioArray") != undefined) {
      for (var i = 0; i < thread.get("audioArray").length; i++) {
        threadObj["audio"].push(getMediaInfo(thread.get("audioArray")[i]));
      }
    }
    if (thread.get("mediaArray") != "" && thread.get("mediaArray") != null && thread.get("mediaArray") != undefined) {
      for (var i = 0; i < thread.get("mediaArray").length; i++) {
        threadObj["media"].push(getMediaInfo(thread.get("mediaArray")[i]));
      }
    }
    //查询赞的数量
    //var enjoyQuery = new AV.Query('Enjoy');
    //enjoyQuery.equalTo("threadOId", thread.id);
    //enjoyQuery.count({
    //	success: function(count) {
    //		threadObj["enjoyNum"]=count;
    //	},error:function(err){
    //		threadObj["enjoyNum"]=0;
    //	}
    //});
  }

  return threadObj;
}

/**
 * 封装媒体信息
 */
exports.getMediaInfo = getMediaInfo;

function getMediaInfo(media) {
  var mediaObj = {};
  if (media != null && media != "" && media != undefined) {
    if (media.get("key") != null) {
      mediaObj["downUrl"] = apis['qiniu']['url'] + media.get("name");
      mediaObj["playUrl"] = apis['qiniu']['url'] + media.get("key");
    } else {
      mediaObj["downUrl"] = "";
    }
    if (media.get("realKey") != null) {
      mediaObj["realUrl"] = apis['qiniu']['url'] + media.get("realKey");
    } else {
      mediaObj["realUrl"] = "";
    }
    if (media.get("name") != null) {
      mediaObj["name"] = media.get("name");
    } else {
      mediaObj["name"] = "";
    }
    if (media.get("size") != null) {
      mediaObj["size"] = media.get("size");
    } else {
      mediaObj["size"] = "";
    }
    if (media.get("widthxHeight") != null) {
      mediaObj["widthxHeight"] = media.get("widthxHeight");
    } else {
      mediaObj["widthxHeight"] = "1x1";
    }
    if (media.get("surfacePic") != null) {
      mediaObj["surfacePic"] = apis['qiniu']['url'] + media.get("surfacePic") + "?imageMogr2/thumbnail/!110px/format/jpg/quality/100/interlace/1/auto-orient";
      mediaObj["surfacePicNormal"] = apis['qiniu']['url'] + media.get("surfacePic");
    } else {
      mediaObj["surfacePic"] = "";
      mediaObj["surfacePicNormal"] = "";
    }
    if (media.get("duration") != null) {
      mediaObj["duration"] = Math.ceil(media.get("duration"));
    } else {
      mediaObj["duration"] = "";
    }
    if (media.get("type") == apis['media']['type_pic']) {
      if (media.get("name") != null) {
        mediaObj["url"] = apis['qiniu']['url'] + media.get("name")
          + apis['pic']['format2'];
        mediaObj["surl"] = apis['qiniu']['url'] + media.get("name")
          + apis['pic']['format'];
        mediaObj["playUrl"] = apis['qiniu']['url']
          + media.get("name") + apis['pic']['format1'];
        mediaObj["downUrl"] = apis['qiniu']['url'] + media.get("name");
      }
      if (media.get("url") != null && media.get("url") != "") {
        mediaObj["url"] = media.get("url") + apis['pic']['format2'];
        mediaObj["surl"] = media.get("url") + apis['pic']['format'];
        mediaObj["playUrl"] = media.get("url") + apis['pic']['format1'];
        mediaObj["downUrl"] = apis['qiniu']['url'] + media.get("url");
      }
    }
  }
  return mediaObj;
}

// 判断是否好友
exports.isFriend = function (userOId, friendOId, callback) {
  if (userOId == "" || userOId == null || userOId == undefined || friendOId == "" || friendOId == null || friendOId == undefined) {
    return callback("", "0");
  } else {
    if (userOId == friendOId) {
      return callback("", "0");
    } else {
      var queryFriend = new AV.Query('FriendRelation');
      queryFriend.equalTo("userOId", userOId);
      queryFriend.equalTo("friendOId", friendOId);
      queryFriend.first({
        success: function (object) {
          var noteName = "";
          if (object != null) {
            isFriend = "1";
            noteName = object.get("noteName");
          } else {
            isFriend = "0";
          }
          return callback(noteName, isFriend);
        }, error: function (err) {
          return callback("", "0");
        }
      });
    }
  }
}
// 判断是否好友
exports.isFriendNew = function (userOId, friendOId, callback) {
  if (userOId == "" || userOId == null || userOId == undefined || friendOId == "" || friendOId == null || friendOId == undefined) {
    return callback("", "0");
  } else {
    if (userOId == friendOId) {
      return callback("", "0");
    } else {
      var queryFriend = new AV.Query('FriendRelation');
      queryFriend.equalTo("userOId", userOId);
      queryFriend.equalTo("friendOId", friendOId);
      queryFriend.first({
        success: function (object) {
          var noteName = "";
          var mlook = "-1";
          var flook = "-1";
          if (object != null) {
            isFriend = "1";
            noteName = object.get("noteName");
            flook = object.get("flook");
          } else {
            isFriend = "0";
          }

          var queryFriend1 = new AV.Query('FriendRelation');
          queryFriend1.equalTo("userOId", friendOId);
          queryFriend1.equalTo("friendOId", userOId);
          queryFriend1.first().then(function (ob) {

            if (ob != null) {
              mlook = ob.get("mlook");
            }

            return callback(noteName, mlook, flook, isFriend);

          }, function (e) {
            return callback("", "-1", "-1", "0");

          })

        }, error: function (err) {
          return callback("", "-1", "-1", "0");
        }
      });
    }
  }
}
// 判断是否部落成员
exports.isTribeMember = function (userOId, tribeOId, callback) {
  var queryFriend = new AV.Query('TribeMember');
  queryFriend.equalTo("userOId", userOId);
  queryFriend.equalTo("tribeOId", tribeOId);
  queryFriend.include("userObj");
//	queryFriend.containedIn("userType", [ "-1","0", "1", "2", "3" ]);
  var userType = "";
  var isTribeMember = "";
  var noteName = "";
  var nickName = ""
  isTribeMember = "0";
  queryFriend.first({
    success: function (object) {
      if (object != null) {
        if (object.get("userType") != "0" && object.get("userType") != "-1")
          isTribeMember = "1";
        userType = object.get("userType");
        noteName = object.get("noteName");
        if (object.get("nickName")) {
          nickName = object.get("nickName");
        } else {
          nickName = object.get("userObj").get("nickName") ? object.get("userObj").get("nickName") : "";
        }
      } else {
        userType = "-2";
      }
      return callback(userType, isTribeMember, noteName, nickName);
    }, error: function (err) {
      return callback(userType, isTribeMember, noteName, nickName);
    }
  });
}
//获取用户与部落的关系
exports.findTribeMember = function (userOId, tribeOId, callback) {
  if (!userOId || !tribeOId) {
    return callback("错误的参数", null);
  } else {
    var queryFriend = new AV.Query('TribeMember');
    queryFriend.equalTo("userOId", userOId);
    queryFriend.equalTo("tribeOId", tribeOId);
    queryFriend.include("tribeObj");
    queryFriend.first().then(function (tribeMemberObj) {
      return callback(null, tribeMemberObj);
    }, function (err) {
      return callback(err.message, null);
    });

  }
}
//获取在部落中的排序序号
exports.getTribeMySortNoByUid = function (userId, callback) {
  if (!userId) {
    return callback("错误的参数", null);
  } else {
    AV.Query.doCloudQuery('select * from TribeMember where (isTop = 0 or isTop is not exists) and userType in ("1", "2", "3") and userObj = pointer("_User", ?) order by mySortNo desc limit 1', [userId])
      .then(function (data) {
        if (data.results.length > 0) {
          var mySortNo = data.results[0].get('mySortNo');
          if (mySortNo == null || mySortNo == '' || mySortNo == undefined)
            mySortNo = 1;
          return callback(null, mySortNo);
        } else {
          return callback(null, 1);
        }
      }, function (error) {
        return callback(error, 0);
      });
  }
}
//用户所有置顶的部落
exports.findTopTribeList = function (userId, callback) {
  if (!userId) {
    return callback("错误的参数", null);
  } else {
    AV.Query.doCloudQuery('select * from TribeMember where isTop = 1 and userObj = pointer("_User", ?) order by mySortNo asc', [userId])
      .then(function (data) {
        return callback(null, data.results);
      }, function (error) {
        return callback(error, null);
      })
  }
}
// 添加好友关系，如果存在则更新
exports.saveFriend = function (userOId, friendOId, callback) {
  var query = new AV.Query('FriendRelation');
  query.equalTo("userOId", userOId);
  query.equalTo("friendOId", friendOId);
  query.first({
    success: function (object) {
      if (object == null) {
        var FriendRelation = getEntity("FriendRelation");
        var friendRelation = new FriendRelation();
        friendRelation.set("userOId", userOId);
        friendRelation.set("friendOId", friendOId);
        friendRelation.set("friendObj", {"__type": "Pointer", className: "_User", objectId: friendOId});
        friendRelation.save(null, {
          success: function (friendRelation) {
            return callback(friendRelation.id);
          },
          error: function (errObj, error) {
            return callback(null);
          }
        });
      } else {
        object.save();
        return callback(object.id);
      }
    },
    error: function (error) {
      return callback(null);
    }
  });
}
exports.getTribeMemberInfo = getTribeMemberInfo;

function getTribeMemberInfo(tribeMember) {
  var tribeObj = {};
  if (tribeMember != null && tribeMember != "" && tribeMember != undefined) {
    if (tribeMember.get("userType") != null) {
      tribeObj["userType"] = tribeMember.get("userType");
    } else {
      tribeObj["userType"] = "";
    }
    if (tribeMember.get("tribeOId") != null) {
      tribeObj["tribeOId"] = tribeMember.get("tribeOId");
    } else {
      tribeObj["tribeOId"] = "";
    }
    if (tribeMember.get("mySortNo") != null) {
      tribeObj["mySortNo"] = tribeMember.get("mySortNo");
    } else {
      tribeObj["mySortNo"] = 0;
    }
    if (tribeMember.get("changeTime") != null) {
      tribeObj["changeTime"] = tribeMember.get("changeTime");
    } else {
      tribeObj["changeTime"] = 0;
    }
    if (tribeMember.get("changeType") != null) {
      tribeObj["changeType"] = tribeMember.get("changeType");
    } else {
      tribeObj["changeType"] = "";
    }
    if (tribeMember.get("tribeObj") != null) {
      tribeObj["tribeObj"] = getTribeInfo(tribeMember.get("tribeObj"));
    } else {
      tribeObj["tribeObj"] = {};
    }
  }
  return tribeObj;
}

exports.getTribeInfo = getTribeInfo;

function getTribeInfo(tribe) {
  var tribeObj = {};
  if (tribe != "" && tribe != null && tribe != undefined) {
    if (tribe.id != null) {
      tribeObj["objectOId"] = tribe.id;
    } else {
      tribeObj["objectOId"] = "";
    }
    if (tribe.get("name") != null) {
      tribeObj["name"] = tribe.get("name");
    } else {
      tribeObj["name"] = "";
    }
    if (tribe.get("num") != null) {
      tribeObj["num"] = tribe.get("num");
    } else {
      tribeObj["num"] = "";
    }
    if (tribe.get("category") != null) {
      tribeObj["category"] = tribe.get("category");
    } else {
      tribeObj["category"] = "";
    }
    if (tribe.get("notice") != null) {
      tribeObj["notice"] = tribe.get("notice");
    } else {
      tribeObj["notice"] = "";
    }
    if (tribe.get("tribeAvator") != null) {
      tribeObj["tribeAvator"] = tribe.get("tribeAvator")._url;
      tribeObj["tribeAvatorId"] = tribe.get("tribeAvator").id;
    } else {
      tribeObj["tribeAvator"] = "";
      tribeObj["tribeAvatorId"] = "";
    }
    if (tribe.get("backgroundImage") != null) {
      tribeObj["backgroundImage"] = tribe.get("backgroundImage")._url;
      tribeObj["backgroundImageId"] = tribe.get("backgroundImage").id;
    } else {
      tribeObj["backgroundImage"] = "";
      tribeObj["backgroundImageId"] = "";
    }
    if (tribe.get("qrCode") != null) {
      tribeObj["qrCode"] = tribe.get("qrCode")._url;
      tribeObj["qrCodeId"] = tribe.get("qrCode").id;
    } else {
      tribeObj["qrCode"] = "";
      tribeObj["qrCodeId"] = "";
    }
    if (tribe.get("backgroundImage") != null) {
      tribeObj["backgroundImage"] = tribe.get("backgroundImage")._url;
      tribeObj["backgroundImageId"] = tribe.get("backgroundImage").id;
    } else {
      tribeObj["backgroundImage"] = apis['qiniu']['url'] + "/" + apis['backgroud']['picName'];
      tribeObj["backgroundImageId"] = apis['backgroud']['id'];
    }
    if (tribe.get("introduction") != null) {
      tribeObj["introduction"] = tribe.get("introduction");
    } else {
      tribeObj["introduction"] = "";
    }
    if (tribe.get("rule") != null) {
      tribeObj["rule"] = tribe.get("rule");
    } else {
      tribeObj["rule"] = "";
    }
    if (tribe.get("verify") != null) {
      tribeObj["verify"] = tribe.get("verify");
    } else {
      tribeObj["verify"] = "";
    }
    if (tribe.get("setAddress") != null) {
      tribeObj["setAddress"] = tribe.get("setAddress");
    } else {
      tribeObj["setAddress"] = 0;
    }
    if (tribe.get("verifyCost") != null) {
      tribeObj["verifyCost"] = tribe.get("verifyCost");
    } else {
      tribeObj["verifyCost"] = "";
    }
    if (tribe.get("generalize") != null) {
      tribeObj["generalize"] = tribe.get("generalize");
    } else {
      tribeObj["generalize"] = 0;
    }
    if (tribe.get("threadRollIn") != null) {
      tribeObj["threadRollIn"] = tribe.get("threadRollIn");
    } else {
      tribeObj["threadRollIn"] = 0;
    }
    if (tribe.get("brandRollIn") != null) {
      tribeObj["brandRollIn"] = tribe.get("brandRollIn");
    } else {
      tribeObj["brandRollIn"] = 0;
    }
    if (tribe.get("postNum") != null) {
      tribeObj["postNum"] = tribe.get("postNum");
    } else {
      tribeObj["postNum"] = 0;
    }
    if (tribe.get("capacity") != null) {
      tribeObj["capacity"] = tribe.get("capacity");
    } else {
      tribeObj["capacity"] = apis['tribeMember']['capacity'];
    }
    if (tribe.get("memberNum") != null) {
      tribeObj["memberNum"] = tribe.get("memberNum");
    } else {
      tribeObj["memberNum"] = 1;
    }
    if (tribe.get("activityNum") != null) {
      tribeObj["activityNum"] = tribe.get("activityNum");
    } else {
      tribeObj["activityNum"] = 0;
    }
    if (tribe.createdAt != null) {
      tribeObj["createdAt"] = tribe.createdAt.getTime().toString();
    } else {
      tribeObj["createdAt"] = "";
    }
    if (tribe.get("isPublic") != null) {
      tribeObj["isPublic"] = tribe.get("isPublic");
    } else {
      tribeObj["isPublic"] = "1";
    }
    if (tribe.get("status") != null) {
      tribeObj["status"] = tribe.get("status");
    } else {
      tribeObj["status"] = "";
    }
  }
  return tribeObj;
}

exports.getRedisTribeInfo = getRedisTribeInfo;

function getRedisTribeInfo(tribe) {
  var tribeObj = {};
  if (tribe != "" && tribe != null && tribe != undefined) {
    if (tribe.objectId != undefined) {
      tribeObj["objectOId"] = tribe.objectId;
    } else {
      tribeObj["objectOId"] = "";
    }
    if (tribe.name != undefined) {
      tribeObj["name"] = tribe.name;
    } else {
      tribeObj["name"] = "";
    }
    if (tribe.num != undefined) {
      tribeObj["num"] = tribe.num;
    } else {
      tribeObj["num"] = "";
    }
    if (tribe.category != undefined) {
      tribeObj["category"] = tribe.category;
    } else {
      tribeObj["category"] = "";
    }
    if (tribe.tribeAvator != undefined) {
      tribeObj["tribeAvator"] = tribe.tribeAvator.url;
      tribeObj["tribeAvatorId"] = tribe.tribeAvator.id;
    } else {
      tribeObj["tribeAvator"] = "";
      tribeObj["tribeAvatorId"] = "";
    }
    if (tribe.qrCode != undefined) {
      tribeObj["qrCode"] = tribe.qrCode.url;
      tribeObj["qrCodeId"] = tribe.qrCode.id;
    } else {
      tribeObj["qrCode"] = "";
      tribeObj["qrCodeId"] = "";
    }
    if (tribe.backgroundImage != undefined) {
      tribeObj["backgroundImage"] = tribe.backgroundImage.url;
      tribeObj["backgroundImageId"] = tribe.backgroundImage.id;
    } else {
      tribeObj["backgroundImage"] = apis['qiniu']['url'] + "/" + apis['backgroud']['picName'];
      tribeObj["backgroundImageId"] = apis['backgroud']['id'];
    }
    if (tribe.introduction != undefined) {
      tribeObj["introduction"] = tribe.introduction;
    } else {
      tribeObj["introduction"] = "";
    }
    if (tribe.rule != undefined) {
      tribeObj["rule"] = tribe.rule;
    } else {
      tribeObj["rule"] = "";
    }
    if (tribe.postNum != undefined) {
      tribeObj["postNum"] = tribe.postNum;
    } else {
      tribeObj["postNum"] = 0;
    }
    if (tribe.capacity != undefined) {
      tribeObj["capacity"] = tribe.capacity;
    } else {
      tribeObj["capacity"] = apis['tribeMember']['capacity'];
    }
    if (tribe.memberNum != undefined) {
      tribeObj["memberNum"] = tribe.memberNum;
    } else {
      tribeObj["memberNum"] = 1;
    }
    if (tribe.activityNum != undefined) {
      tribeObj["activityNum"] = tribe.activityNum;
    } else {
      tribeObj["activityNum"] = 0;
    }
    if (tribe.createdAt != undefined) {
      tribeObj["createdAt"] = new Date(tribe.createdAt).getTime().toString();
    } else {
      tribeObj["createdAt"] = "";
    }
    if (tribe.isPublic != undefined) {
      tribeObj["isPublic"] = tribe.isPublic;
    } else {
      tribeObj["isPublic"] = "1";
    }
    if (tribe.status != undefined) {
      tribeObj["status"] = tribe.status;
    } else {
      tribeObj["status"] = "";
    }
  }
  return tribeObj;
}

exports.getWebTribeInfo = getWebTribeInfo;

function getWebTribeInfo(tribe) {
  var tribeObj = {};
  if (tribe != "" && tribe != null && tribe != undefined) {
    if (tribe.id != null) {
      tribeObj["objectOId"] = tribe.id;
    } else {
      tribeObj["objectOId"] = "";
    }
    if (tribe.get("createrObj") != null) {
      tribeObj["createrObj"] = getUserInfo(tribe.get("createrObj"));
    } else {
      tribeObj["createrObj"] = {};
    }
    if (tribe.get("name") != null) {
      tribeObj["name"] = tribe.get("name");
    } else {
      tribeObj["name"] = "";
    }
    if (tribe.get("num") != null) {
      tribeObj["num"] = tribe.get("num");
    } else {
      tribeObj["num"] = "";
    }
    if (tribe.get("category") != null) {
      tribeObj["category"] = tribe.get("category");
    } else {
      tribeObj["category"] = "";
    }
    if (tribe.get("tribeAvator") != null
      && tribe.get("tribeAvator") != undefined) {
      var aurl = tribe.get("tribeAvator")._url;
      if (aurl == undefined)
        aurl = tribe.get("tribeAvator").get("url");
      tribeObj["tribeAvator"] = aurl;
      tribeObj["tribeAvatorId"] = tribe.get("tribeAvator").id;
    } else {
      tribeObj["tribeAvator"] = "";
      tribeObj["tribeAvatorId"] = "";
    }
    if (tribe.get("backgroundImage") != null
      && tribe.get("backgroundImage") != undefined) {
      var burl = tribe.get("backgroundImage")._url;
      if (burl == undefined)
        burl = tribe.get("backgroundImage").get("url");
      tribeObj["backgroundImage"] = aurl;
      tribeObj["backgroundImageId"] = tribe.get("backgroundImage").id;
    } else {
      tribeObj["backgroundImage"] = "";
      tribeObj["backgroundImageId"] = "";
    }
    if (tribe.get("qrCode") != null && tribe.get("qrCode") != undefined) {
      var qurl = tribe.get("qrCode")._url;
      if (qurl == undefined)
        qurl = tribe.get("qrCode").get("url");
      tribeObj["qrCode"] = qurl;
      tribeObj["qrCodeId"] = tribe.get("qrCode").id;
    } else {
      tribeObj["qrCode"] = "";
      tribeObj["qrCodeId"] = "";
    }
    if (tribe.get("backgroundImage") != null
      && tribe.get("backgroundImage") != undefined) {
      var burl = "";
      burl = tribe.get("backgroundImage")._url;
      if (burl == undefined)
        burl = tribe.get("backgroundImage").get("url");
      tribeObj["backgroundImage"] = burl;
      tribeObj["backgroundImageId"] = tribe.get("backgroundImage").id;
    } else {
      tribeObj["backgroundImage"] = "";
      tribeObj["backgroundImageId"] = "";
    }
    if (tribe.get("introduction") != null) {
      tribeObj["introduction"] = tribe.get("introduction");
    } else {
      tribeObj["introduction"] = "";
    }
    if (tribe.get("rule") != null) {
      tribeObj["rule"] = tribe.get("rule");
    } else {
      tribeObj["rule"] = "";
    }
    if (tribe.get("postNum") != null) {
      tribeObj["postNum"] = tribe.get("postNum");
    } else {
      tribeObj["postNum"] = 0;
    }
    if (tribe.get("capacity") != null) {
      tribeObj["capacity"] = tribe.get("capacity");
    } else {
      tribeObj["capacity"] = apis['tribeMember']['capacity'];
    }
    if (tribe.get("memberNum") != null) {
      tribeObj["memberNum"] = tribe.get("memberNum");
    } else {
      tribeObj["memberNum"] = 1;
    }
    if (tribe.get("activityNum") != null) {
      tribeObj["activityNum"] = tribe.get("activityNum");
    } else {
      tribeObj["activityNum"] = 0;
    }
    if (tribe.createdAt != null) {
      tribeObj["createdAt"] = formatDate(tribe.createdAt, null);
    } else {
      tribeObj["createdAt"] = "";
    }
  }
  return tribeObj;
}

// 字典信息
exports.getDictionaryInfo = function (dictionary) {
  var dictionaryObj = {};
  if (dictionary != "" && dictionary != null && dictionary != undefined) {
    if (dictionary.id != null) {
      dictionaryObj["objectOId"] = dictionary.id;
    } else {
      dictionaryObj["objectOId"] = "";
    }
    if (dictionary.get("name") != null) {
      dictionaryObj["name"] = dictionary.get("name");
    } else {
      dictionaryObj["name"] = "";
    }
    if (dictionary.get("code") != null) {
      dictionaryObj["code"] = dictionary.get("code");
    } else {
      dictionaryObj["code"] = "";
    }
    if (dictionary.get("fatherCode") != null) {
      dictionaryObj["fatherCode"] = dictionary.get("fatherCode");
    } else {
      dictionaryObj["fatherCode"] = "";
    }
    if (dictionary.get("icon") != null) {
      dictionaryObj["icon"] = dictionary.get("icon")._url;
      dictionaryObj["iconId"] = dictionary.get("icon").id;
    } else {
      dictionaryObj["icon"] = "";
      dictionaryObj["iconId"] = "";
    }
    if (dictionary.get("type") != null) {
      dictionaryObj["type"] = dictionary.get("type");
    } else {
      dictionaryObj["type"] = "";
    }
    if (dictionary.get("status") != null) {
      dictionaryObj["status"] = dictionary.get("status");
    } else {
      dictionaryObj["status"] = "";
    }
    if (dictionary.get("isHot") != null) {
      dictionaryObj["isHot"] = dictionary.get("isHot");
    } else {
      dictionaryObj["isHot"] = "";
    }
    if (dictionary.get("level") != null) {
      dictionaryObj["level"] = dictionary.get("level");
    } else {
      dictionaryObj["level"] = "";
    }
    if (dictionary.get("sortNum") != null) {
      dictionaryObj["sortNum"] = dictionary.get("sortNum");
    } else {
      dictionaryObj["sortNum"] = "";
    }
  }
  return dictionaryObj;
}
//我的虚拟账户
exports.getShopAccountInfo = getShopAccountInfo;

function getShopAccountInfo(module) {
  var dictionaryObj = {};
  if (module != "" && module != null && module != undefined) {
    if (module.id != null) {
      dictionaryObj["objectId"] = module.id;
    } else {
      dictionaryObj["objectId"] = "";
    }
    if (module.get("currentMoney") != null) {
      dictionaryObj["currentMoney"] = formatMoneyFixed(module.get("currentMoney"));
    } else {
      dictionaryObj["currentMoney"] = 0;
    }
    if (module.get("frozenMoney") != null) {
      dictionaryObj["frozenMoney"] = formatMoneyFixed(module.get("frozenMoney"));
    } else {
      dictionaryObj["frozenMoney"] = 0;
    }
    if (module.get("withdrawMoney") != null) {
      dictionaryObj["withdrawMoney"] = formatMoneyFixed(module.get("withdrawMoney"));
    } else {
      dictionaryObj["withdrawMoney"] = 0;
    }
    if (module.get('withdrawFrozenMoney') != null) {
      dictionaryObj['withdrawFrozenMoney'] = formatMoneyFixed(module.get('withdrawFrozenMoney'));
    } else {
      dictionaryObj['withdrawFrozenMoney'] = 0;
    }
    if (module.get("userOId") != null) {
      dictionaryObj["userOId"] = module.get("userOId");
    } else {
      dictionaryObj["userOId"] = "";
    }
    if (module.get("userObj") != null) {
      dictionaryObj["userObj"] = getUserInfo(module.get("userObj"));
    } else {
      dictionaryObj["userObj"] = "";
    }
  }
  return dictionaryObj;
}

//账户明细
exports.getShopAccountDetailInfo = getShopAccountDetailInfo;

function getShopAccountDetailInfo(module) {
  var dictionaryObj = {};
  if (module != "" && module != null && module != undefined) {
    if (module.id != null) {
      dictionaryObj["objectId"] = module.id;
    } else {
      dictionaryObj["objectId"] = "";
    }
    if (module.get("changeType") != null) {
      dictionaryObj["changeType"] = module.get("changeType");
    } else {
      dictionaryObj["changeType"] = "";
    }
    if (module.get("bankName") != null) {
      dictionaryObj["bankName"] = module.get("bankName");
    } else {
      dictionaryObj["bankName"] = "";
    }
    if (module.get("name") != null) {
      dictionaryObj["name"] = module.get("name");
    } else {
      dictionaryObj["name"] = "";
    }
    if (module.get("bankNo") != null) {
      dictionaryObj["bankNo"] = module.get("bankNo");
    } else {
      dictionaryObj["bankNo"] = "";
    }
    if (module.get("userOId") != null) {
      dictionaryObj["userOId"] = module.get("userOId");
    } else {
      dictionaryObj["userOId"] = "";
    }
    if (module.get("userObj") != null) {
      dictionaryObj["userObj"] = getUserInfo(module.get("userObj"));
    } else {
      dictionaryObj["userObj"] = {};
    }
    if (module.get("orderNo") != null) {
      dictionaryObj["orderNo"] = module.get("orderNo");
    } else {
      dictionaryObj["orderNo"] = 0;
    }
    if (module.get("procedureFee") != null) {
      dictionaryObj["procedureFee"] = formatMoneyFixed(module.get("procedureFee"));
    } else {
      dictionaryObj["procedureFee"] = 0;
    }
    if (module.get("changeMoney") != null) {
      dictionaryObj["changeMoney"] = formatMoneyFixed(module.get("changeMoney"));
      dictionaryObj["changeOkMoney"] = formatMoney(module.get("changeMoney") - parseFloat(dictionaryObj["procedureFee"]));
    } else {
      dictionaryObj["changeOkMoney"] = 0;
      dictionaryObj["changeMoney"] = 0;
    }
    if (module.get("procedureRate") != null) {
      dictionaryObj["procedureRate"] = module.get("procedureRate").toString();
    } else {
      dictionaryObj["procedureRate"] = "0";
    }
    if (module.get("remark") != null) {
      if ("部落佣金" == module.get("remark")) {
        dictionaryObj["remark"] = "推广收益";
      } else if ("销售收入" == module.get("remark")) {
        dictionaryObj["remark"] = "销售收益";
      }
      else if ("推广分成" == module.get("remark")) {
        dictionaryObj["remark"] = "分享收益";
      } else {
        dictionaryObj["remark"] = module.get("remark");
      }

    } else {
      dictionaryObj["remark"] = "";
    }
    if (module.get("withdrawStatus") != null) {
      dictionaryObj["withdrawStatus"] = module.get("withdrawStatus");
    } else {
      dictionaryObj["withdrawStatus"] = "";
    }
    if (module.get("status") != null) {
      dictionaryObj["status"] = 1;
    } else {
      dictionaryObj["status"] = 1;
    }
    if (module.createdAt != null) {
      dictionaryObj["createTime"] = module.createdAt.getTime();
    } else {
      dictionaryObj["createTime"] = 0;
    }
    if (module.createdAt != null) {
      dictionaryObj["createDate"] = formatDateNormal(module.createdAt, null);
    } else {
      dictionaryObj["createDate"] = 0;
    }
  }
  return dictionaryObj;
}

//分享赚钱评论
exports.getPostShareInfo = getPostShareInfo;

function getPostShareInfo(module) {
  var dictionaryObj = {};
  if (module != "" && module != null && module != undefined) {
    if (module.id != null) {
      dictionaryObj["objectId"] = module.id;
    } else {
      dictionaryObj["objectId"] = "";
    }
    if (module.get("content") != null) {
      dictionaryObj["content"] = module.get("content");
    } else {
      dictionaryObj["content"] = "";
    }
    if (module.get("shareGoodsOId") != null) {
      dictionaryObj["shareGoodsOId"] = module.get("shareGoodsOId");
    } else {
      dictionaryObj["shareGoodsOId"] = "";
    }
    if (module.get("enjoyNum") != null) {
      dictionaryObj["enjoyNum"] = module.get("enjoyNum");
    } else {
      dictionaryObj["enjoyNum"] = 0;
    }
    if (module.get("userOId") != null) {
      dictionaryObj["userOId"] = module.get("userOId");
    } else {
      dictionaryObj["userOId"] = "";
    }
    if (module.get("userObj") != null) {
      dictionaryObj["userObj"] = getUserInfo(module.get("userObj"));
    } else {
      dictionaryObj["userObj"] = {};
    }
    if (module.get("personOId") != null) {
      dictionaryObj["personOId"] = module.get("personOId");
    } else {
      dictionaryObj["personOId"] = "";
    }
    if (module.get("personObj") != null) {
      dictionaryObj["personObj"] = getUserInfo(module.get("personObj"));
    } else {
      dictionaryObj["personObj"] = {};
    }
    var pics = [];
    if (module.get("picArray") != null) {

      for (var i = 0; i < module.get("picArray").length; i++) {

        if (module.get("picArray")[i] != null)

          pics.push(getShareGoodsPic(module.get("picArray")[i]));
      }

    }
    dictionaryObj["pics"] = pics;
    if (module.createdAt != null) {
      dictionaryObj["createTime"] = module.createdAt.getTime();
    } else {
      dictionaryObj["createTime"] = 0;
    }
  }
  return dictionaryObj;
}

//模块信息
exports.getModuleInfo = function (module) {
  var dictionaryObj = {};
  if (module != "" && module != null && module != undefined) {
    if (module.id != null) {
      dictionaryObj["objectId"] = module.id;
    } else {
      dictionaryObj["objectId"] = "";
    }
    if (module.get("name") != null) {
      dictionaryObj["name"] = module.get("name");
    } else {
      dictionaryObj["name"] = "";
    }
    if (module.get("title") != null) {
      dictionaryObj["title"] = module.get("title");
    } else {
      dictionaryObj["title"] = "";
    }
    if (module.get("sortNum") != null) {
      dictionaryObj["sortNum"] = module.get("sortNum");
    } else {
      dictionaryObj["sortNum"] = "";
    }
  }
  return dictionaryObj;
}
//查询正常用户
exports.getNormalUserByOId = getNormalUserByOId;

function getNormalUserByOId(oId, callback) {
  if (oId == "" && oId == null) {
    return callback(null);
  }
  var query = new AV.Query('_User');
  query.equalTo("objectId", oId);
  query.notEqualTo("status", "0");
  query.first({
    success: function (object) {
      return callback(object);
    }, error: function (err) {
      return callback(null);
    }
  });
}

// 根据用户id查询用户
exports.getUserByOId = getUserByOId;

function getUserByOId(OId, callback) {
  var query = new AV.Query('_User');
  query.equalTo("objectId", OId);
  query.first({
    success: function (object) {
      return callback(object);
    }, error: function (err) {
      return callback(null);
    }
  });
}

// 根据用户id数组查询用户集合
exports.getUsersByOIds = function (usersArrValue, callback) {
  var query = new AV.Query('_User');
  query.containedIn("objectId", usersArrValue);
  query.limit(1000);
  query.find({
    success: function (objects) {
      return callback(objects);
    }, error: function (err) {
      return callback(null);
    }
  });
}

function indexOfMy(arry, obj) {
  for (var i = 0; i < arry.length; i++) {
    if (obj != null && arry[i] != null) {
      if (JSON.stringify(arry[i]) == JSON.stringify(obj)) {
        return i;
      }
    }
  }
  return -1;
}

/**
 * 统计对象在集合中出现的次数
 */
function arryShowNum(arry, Object) {
  var num = 0;
  for (var i = 0; i < arry.length; i++) {
    if (JSON.stringify(arry[i]) == JSON.stringify(Object)) {
      num++;
    }
  }
  return num;
}

/**
 * 数组去重(保留一个重复的对象，此处只是逻辑去重，两个对象完全一致才视为重复，如果判断业务重复，请另写类似方法,只需将if处与下一行的代码换成n[arry[i].要判断的属性名])即可
 */
exports.arrayDistinctStr = arrayDistinctStr;

function arrayDistinctStr(arry) {
  var n = {}, r = []; // n为hash表，r为临时数组
  for (var i = 0; i < arry.length; i++) // 遍历当前数组
  {
    if (!n[JSON.stringify(arry[i])]) // 如果hash表中没有当前项
    {
      n[JSON.stringify(arry[i])] = true; // 存入hash表
      r.push(arry[i]); // 把当前数组的当前项push到临时数组里面
    }
  }
  return r;
}

/**
 * 数组去重(不保留一个重复对象，此处只是逻辑去重，两个对象完全一致才视为重复，如果判断业务重复，请另写类似方法,只需将if处与下一行的代码换成n[arry[i].要判断的属性名])即可
 */
exports.arrayDistinctStr1 = arrayDistinctStr1;

function arrayDistinctStr1(arry) {
  var arr1 = arrayDistinctStr(arry);
  for (var i = 0; i < arr1.length; i++) {
    var showNum = arryShowNum(arry, arr1[i]);
    if (showNum > 1) {
      for (var j = showNum; j > 0; j--) {
        arry.splice(indexOfMy(arry, arr1[i]), 1);
      }
    }
  }
  return arry;
}

/**
 * 读取数组中重复数据
 */
exports.arrayDistinctStr2 = arrayDistinctStr2;

function arrayDistinctStr2(arry) {
  var returnArry = [];
  var arr1 = arrayDistinctStr(arry);
  for (var i = 0; i < arr1.length; i++) {
    var showNum = arryShowNum(arry, arr1[i]);
    if (showNum > 1) {
      returnArry.push(arr1[i]);
    }
  }
  return returnArry;
}

exports.arrayDistinctStr3 = arrayDistinctStr3;

function arrayDistinctStr3(arry) {
  var returnArry = [];
  var arr1 = arrayDistinctStr(arry);
  for (var i = 0; i < arr1.length; i++) {
    var showNum = arryShowNum3(arry, arr1[i]);
    if (showNum > 1) {
      returnArry.push(arr1[i]);
    }
  }
  return returnArry;
}

function arryShowNum3(arry, Object) {
  var num = 0;
  for (var i = 0; i < arry.length; i++) {
    if (arry[i].get("mySortNo") == Object.get("mySortNo")) {
      num++;
    }
  }
  return num;
}

/**
 * 去除无效手机号(有效手机号：13[0-9]|15[0-9]|18[0-9]|17[0|6|7|8]\d{8})
 */
exports.regTel = function (arry) {
  // 删除空格以及去除+86、86等无效信息
  for (var i = 0; i < arry.length; i++) {
    arry[i].tel = arry[i].tel.TrimAll();
    if (arry[i].tel.indexOf("+86") == 0) {
      arry[i].tel = arry[i].tel.substring(3);
    }
    if (arry[i].tel.indexOf("86") == 0) {
      arry[i].tel = arry[i].tel.substring(2);
    }
  }
  // 正则匹配手机号格式
  var reg = /^(13[0-9]|15[0-9]|18[0-9]|17[0|6|7|8]|14[0|6|7|8])\d{8}$/;
  for (var i = 0; i < arry.length; i++) {
    if (!reg.test(arry[i].tel)) {
      arry.splice(i, 1);
      i--;
    }
  }
  return arry;
}
/**
 * 通过key查询media
 */
exports.queryMediaByKey = function (key, callback) {
  if (key == "" || key == null || key == undefined)
    return callback(null);
  var query = new AV.Query('Media');
  query.equalTo("name", key);
  query.first({
    success: function (object) {
      return callback(object);
    },
    error: function (error) {
      return callback(null);
    }
  });
}
/**
 * 对media中的图片的操作（如果没有创建否则更新）
 */
exports.processMediaPic = function (uId, picArr, thread, callback) {
  var picsArrValue = [];
  var picsNameArrValue = [];
  if (picArr != null && picArr != undefined) {
    for (var i = 0; i < picArr.length; i++) {
      if (picArr[i].objectId != null && picArr[i].objectId != "") {
        picsArrValue.push(picArr[i].objectId);
        picsNameArrValue[picArr[i].objectId] = i + 1;
      }
    }
  }
  if (picsArrValue.length > 0) {
    var query = new AV.Query('Media');
    query.containedIn("name", picsArrValue);
    query.find({
      success: function (medias) {
        var objects = [];
        for (var i = 0; i < medias.length; i++) {
          picsArrValue.splice(picsArrValue.indexOf(medias[i].get("name")), 1);
          medias[i].set("threadOId", thread.id);
          medias[i].set("sortNum", picsNameArrValue[medias[i].get("name")]);
          medias[i].set("userOId", uId);
          objects.push(medias[i]);
        }
        // 未查询到的数据新增到数据库中
        var newMedia = null;
        var Media = getEntity("Media");
        for (var i = 0; i < picsArrValue.length; i++) {
          newMedia = new Media();
          newMedia.set("name", picsArrValue[i]);
          newMedia.set("fromType", apis['media']['form_thread']);
          newMedia.set("type", apis['media']['type_pic']);
          newMedia.set("threadOId", thread.id);
          newMedia.set("sortNum", picsNameArrValue[picsArrValue[i]]);
          newMedia.set("status", "0");
          newMedia.set("userOId", uId);
          objects.push(newMedia);
        }
        AV.Object.saveAll(objects, function (list, error) {
          if (error == null) {
            var isAll = false;
            if (picsArrValue.length == medias.length)
              isAll = true;
            return callback("1", null, list, isAll);
          } else {
            return callback("0", error, null, null);
          }
        });
      },
      error: function (error) {
        return callback("0", error.message, null, null);
      }
    });
  } else {
    return callback("0", "无效的数据", null, null);
  }
}
/**
 * 对media中的音视频的操作（如果没有创建否则更新）
 */
exports.processMediaVoice = function (uId, key, type, thread, callback) {
  if (key != null && key != "" && key != undefined) {
    var query = new AV.Query('Media');
    query.equalTo("name", key);
    query.first({
      success: function (mediaObj) {
        var media = null;
        var Media = getEntity("Media");
        if (mediaObj == null) {
          media = new Media();
          media.set("name", key);
          media.set("status", "0");
        } else {
          media = mediaObj;
        }
        media.set("threadOId", thread.id);
        media.set("fromType", "1");
        media.set("type", type);
        if (type == "2")
          media.set("sortNum", 999);
        else if (type == "3")
          media.set("sortNum", 1000);
        media.set("userOId", uId);
        media.save(null, {
          success: function (media) {
            var mediaArray = [];
            mediaArray.push(media);
            var isAll = false;
            if (mediaObj != null)
              mediaObj = true;
            return callback("1", null, mediaArray, isAll);
          }, error: function (errObj, error) {
            return callback("0", error.message, null, false);
          }
        })
      }, error: function (error) {
        return callback("0", error.message, null, false);
      }
    });
  } else {
    return callback("0", "无效的数据", null, false);
  }
}
/**
 * 格式化日期，缺省样式是“yyyy-MM-dd HH:mm:ss”
 */
exports.formatDate = formatDate;

function formatDate(date, style) {
  var cSs = new Date().getTime() - date.getTime();
  if (cSs <= 3600000) {
    var min = parseInt(cSs / 1000 / 60);
    if (min == 0)
      return "刚刚";
    else
      return min + "分钟前";
  }
  if (date.toLocaleString().indexOf("UTC") > -1)
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  if (style == null)
    style = "yyyy-MM-dd HH:mm:ss";
  var y = date.getFullYear();
  var M = "0" + (date.getMonth() + 1);
  M = M.substring(M.length - 2);
  var d = "0" + date.getDate();
  d = d.substring(d.length - 2);
  var h = "0" + date.getHours();
  h = h.substring(h.length - 2);
  if (h >= 0 && h < 6)
    h = "凌晨 " + h;
  else if (h >= 6 && h < 12)
    h = "上午 " + h;
  else if (h >= 12 && h < 18)
    h = "下午 " + h;
  else if (h >= 18 && h < 24)
    h = "晚上 " + h;
  var m = "0" + date.getMinutes();
  m = m.substring(m.length - 2);
  var s = "0" + date.getSeconds();
  s = s.substring(s.length - 2);
  return style.replace('yyyy', y).replace('MM', M).replace('dd', d).replace(
    'HH', h).replace('mm', m).replace('ss', s);
}

exports.formatDateNormal = formatDateNormal;

function formatDateNormal(date, style) {
  if (date == "" || date == null || date == undefined) {
    return "";
  }
  var cSs = new Date().getTime() - date.getTime();
  if (date.toLocaleString().indexOf("UTC") > -1)
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  if (style == null)
    style = "yyyy-MM-dd HH:mm:ss";
  var y = date.getFullYear();
  var M = "0" + (date.getMonth() + 1);
  M = M.substring(M.length - 2);
  var d = "0" + date.getDate();
  d = d.substring(d.length - 2);
  var h = "0" + date.getHours();
  h = h.substring(h.length - 2);
  var m = "0" + date.getMinutes();
  m = m.substring(m.length - 2);
  var s = "0" + date.getSeconds();
  s = s.substring(s.length - 2);
  return style.replace('yyyy', y).replace('MM', M).replace('dd', d).replace(
    'HH', h).replace('mm', m).replace('ss', s);
}

exports.formatDateDay = formatDateDay;

function formatDateDay(date, style) {
  var cSs = new Date().getTime() - date.getTime();
  if (date.toLocaleString().indexOf("UTC") > -1)
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  if (style == null)
    style = "yyyy-MM-dd";
  var y = date.getFullYear();
  var M = "0" + (date.getMonth() + 1);
  M = M.substring(M.length - 2);
  var d = "0" + date.getDate();
  d = d.substring(d.length - 2);
  return style.replace('yyyy', y).replace('MM', M).replace('dd', d);
}

exports.getCurrDayBeginTime = getCurrDayBeginTime;

function getCurrDayBeginTime() {
  var today = new Date();
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  today.setMilliseconds(0);
  if (today.toLocaleString().indexOf("UTC") > -1)
    return today.getTime() - 8 * 60 * 60 * 1000;
  else
    return today.getTime();
}

exports.getCurrDayEndTime = getCurrDayEndTime;

function getCurrDayEndTime() {
  var today = new Date();
  today.setHours(23);
  today.setMinutes(59);
  today.setSeconds(59);
  today.setMilliseconds(0);
  if (today.toLocaleString().indexOf("UTC") > -1)
    return today.getTime() - 8 * 60 * 60 * 1000;
  else
    return today.getTime();
}

exports.getCurrTime = getCurrTime;

function getCurrTime() {
  var today = new Date();
  if (today.toLocaleString().indexOf("UTC") > -1)
    return today.getTime() - 8 * 60 * 60 * 1000;
  else
    return today.getTime();
}

/**
 * 处理重复media
 */
exports.updateSameMedia = function (key, callback) {
  var query = new AV.Query('Media');
  query.equalTo("name", key);
  query.find({
    success: function (objects) {
      if (objects != null) {
        // 长度大于1才视为产生了并发数据
        if (objects.length > 1) {
          // 取出有threadOId的一个
          var threadMedia = null;
          var removeArry = [];
          for (var i = 0; i < objects.length; i++) {
            if (objects[i].get("threadOId") != null
              && objects[i].get("threadOId") != ""
              && threadMedia == null) {
              threadMedia = objects[i];
            } else {
              removeArry.push(objects[i]);
            }
          }
          if (threadMedia == null) {
            threadMedia = objects[0];
          } else {
            if (objects[0].get("size") != null)
              threadMedia.set("size", objects[0].get("size"));
            if (objects[0].get("key") != null)
              threadMedia.set("key", objects[0].get("key"));
            if (objects[0].get("duration") != null)
              threadMedia.set("duration", objects[0]
                .get("duration"));
            if (objects[0].get("realKey") != null)
              threadMedia.set("realKey", objects[0]
                .get("realKey"));
            threadMedia.set("status", "1");
          }
          threadMedia.save();
          AV.Object.destroyAll(removeArry);
        }
      } else {
      }
      return callback(null);
    }, error: function (err) {
      return callback(null);
    }
  });
}

/**
 * 封装商品基本信息
 */
exports.getGoodsBaseInfo = getGoodsBaseInfo;

function getGoodsBaseInfo(goods) {
  var goodsObj = {};
  if (goods != "" && goods != null && goods != undefined) {
    if (goods.id != null) {
      goodsObj["objectId"] = goods.id;
    } else {
      goodsObj["objectId"] = "";
    }
    if (goods.get("goodNo") != null) {
      goodsObj["goodNo"] = goods.get("goodNo");
    } else {
      goodsObj["goodNo"] = "";
    }
    if (goods.get("collectionNum") != null) {
      goodsObj["collectionNum"] = goods.get("collectionNum");
    } else {
      goodsObj["collectionNum"] = 0;
    }
    if (goods.get("describe") != null) {
      goodsObj["describe"] = goods.get("describe");
    } else {
      goodsObj["describe"] = "";
    }
    if (goods.get("freePost") != null) {
      goodsObj["freePost"] = goods.get("freePost");
    } else {
      goodsObj["freePost"] = "";
    }
    if (goods.get("price") != null) {
      goodsObj["price"] = formatMoneyFixed(goods.get("price"));
    } else {
      goodsObj["price"] = "0";
    }
    if (goods.get("recommend") != null) {
      goodsObj["recommend"] = goods.get("recommend");
    } else {
      goodsObj["recommend"] = "";
    }
    if (goods.get("saleNums") != null) {
      goodsObj["saleNums"] = goods.get("saleNums");
    } else {
      goodsObj["saleNums"] = 0;
    }
    if (goods.get("shopCategory") != null) {
      goodsObj["shopCategory"] = goods.get("shopCategory");
    } else {
      goodsObj["shopCategory"] = "";
    }
    if (goods.get("status") != null) {
      goodsObj["status"] = goods.get("status");
    } else {
      goodsObj["status"] = 0;
    }
    if (goods.get("sysCategory") != null) {
      goodsObj["sysCategory"] = goods.get("sysCategory");
    } else {
      goodsObj["sysCategory"] = "";
    }
    if (goods.get("title") != null) {
      goodsObj["title"] = goods.get("title");
    } else {
      goodsObj["title"] = "";
    }
  }
  return goodsObj;
}

/**
 * 前往编辑商品封装商品基本信息
 */
exports.getEditGoodsBaseInfo = getEditGoodsBaseInfo;

function getEditGoodsBaseInfo(goods) {
  var goodsObj = {};
  if (goods != "" && goods != null && goods != undefined) {
    if (goods.id != null) {
      goodsObj["objectId"] = goods.id;
    } else {
      goodsObj["objectId"] = "";
    }
    if (goods.get("goodNo") != null) {
      goodsObj["goodNo"] = goods.get("goodNo");
    } else {
      goodsObj["goodNo"] = "";
    }
    if (goods.get("collectionNum") != null) {
      goodsObj["collectionNum"] = goods.get("collectionNum");
    } else {
      goodsObj["collectionNum"] = 0;
    }
    if (goods.get("describe") != null) {
      goodsObj["describe"] = goods.get("describe");
    } else {
      goodsObj["describe"] = "";
    }
    if (goods.get("freePost") != null) {
      goodsObj["freePost"] = goods.get("freePost");
    } else {
      goodsObj["freePost"] = "";
    }
    if (goods.get("price") != null) {
      goodsObj["price"] = formatMoneyFixed(goods.get("price"));
    } else {
      goodsObj["price"] = "0";
    }


    if (goods.get("label") != null) {
      goodsObj["label"] = (goods.get("label"));
    } else {
      goodsObj["label"] = "";
    }
    if (goods.get("discount") != null) {
      goodsObj["discount"] = (goods.get("discount"));
    } else {
      goodsObj["discount"] = 10;
    }
    if (goods.get("originalPrice") != null) {
      goodsObj["originalPrice"] = formatMoneyFixed(goods.get("originalPrice"));
    } else {
      goodsObj["originalPrice"] = formatMoneyFixed(goods.get("price"));
    }
    if (goods.get("picName") != null && goods.get("picName") != "") {
      if (goods.get("picName").indexOf("http://") == -1)
        goodsObj["surfacePic"] = apis['qiniu']['url'] + "/" + goods.get("picName");
      else
        goodsObj["surfacePic"] = goods.get("picName");
      goodsObj["surfacePicId"] = "";
    } else {
      if (goods.get("surfacePic") != null) {
        var aurl = goods.get("surfacePic")._url;
        if (aurl == undefined)
          aurl = goods.get("surfacePic").get("url");
        goodsObj["surfacePic"] = aurl;
        goodsObj["surfacePicId"] = goods.get("surfacePic").id;
      } else {
        goodsObj["surfacePic"] = "";
        goodsObj["surfacePicId"] = "";
      }
    }


    if (goods.get("recommend") != null) {
      goodsObj["recommend"] = goods.get("recommend");
    } else {
      goodsObj["recommend"] = "";
    }
    if (goods.get("groupCommission") != null) {
      goodsObj["groupCommission"] = goods.get("groupCommission");
    } else {
      goodsObj["groupCommission"] = 0;
    }
    if (goods.get("saleNums") != null) {
      goodsObj["saleNums"] = goods.get("saleNums");
    } else {
      goodsObj["saleNums"] = 0;
    }
    if (goods.get("shopCategory") != null) {
      goodsObj["shopCategory"] = goods.get("shopCategory");
    } else {
      goodsObj["shopCategory"] = "";
    }
    if (goods.get("status") != null) {
      goodsObj["status"] = goods.get("status");
    } else {
      goodsObj["status"] = 0;
    }
    if (goods.get("sysCategory") != null) {
      goodsObj["sysCategory"] = goods.get("sysCategory");
    } else {
      goodsObj["sysCategory"] = "";
    }
    if (goods.get("title") != null) {
      goodsObj["title"] = goods.get("title");
    } else {
      goodsObj["title"] = "";
    }
    if (goods.get("groupBuying") != null) {
      goodsObj["groupBuying"] = goods.get("groupBuying");
    } else {
      goodsObj["groupBuying"] = 0;
    }
    if (goods.get("groupPrice") != null) {
      goodsObj["groupPrice"] = goods.get("groupPrice");
    } else {
      goodsObj["groupPrice"] = 0;
    }
    if (goods.get("promote") != null) {
      goodsObj["promote"] = parseInt(goods.get("promote") * 100);
    } else {
      goodsObj["promote"] = 0;
    }
    if (goods.get("promotionPrice") != null) {
      goodsObj["promotionPrice"] = goods.get("promotionPrice");
    } else {
      goodsObj["promotionPrice"] = goods.get("price");
    }
    goodsObj.customize = goods.get("customize");
  }
  return goodsObj;
}

/**
 * 封装卖家商品信息
 */
exports.getSellerGoodsInfo = getSellerGoodsInfo;

function getSellerGoodsInfo(goods) {
  var goodsObj = {};
  if (goods != "" && goods != null && goods != undefined) {
    if (goods.id != null) {
      goodsObj["objectId"] = goods.id;
    } else {
      goodsObj["objectId"] = "";
    }
    if (goods.get("price") != null) {
      goodsObj["price"] = formatMoneyFixed(goods.get("price"));
    } else {
      goodsObj["price"] = "0";
    }
    if (goods.get("promotionPrice") != null) {
      goodsObj["promotionPrice"] = formatMoneyFixed(goods.get("promotionPrice"));
    } else {
      goodsObj["promotionPrice"] = formatMoneyFixed(goods.get("price"));
    }
    if (goods.get("originaPrice") != null) {

      goodsObj["originaPrice"] = formatMoneyFixed(goods.get("originaPrice"));
    } else {
      goodsObj["originaPrice"] = "";
    }
    if (goods.get("saleNums") != null) {
      goodsObj["saleNums"] = goods.get("saleNums");
    } else {
      goodsObj["saleNums"] = 0;
    }
    if (goods.get("stock") != null) {
      goodsObj["stock"] = goods.get("stock");
    } else {
      goodsObj["stock"] = 0;
    }
    if (goods.get("status") != null) {
      goodsObj["status"] = goods.get("status");
    } else {
      goodsObj["status"] = 0;
    }
    if (goods.get("picName") != null && goods.get("picName") != "") {
      if (goods.get("picName").indexOf("http://") == -1)
        goodsObj["surfacePic"] = apis['qiniu']['url'] + "/" + goods.get("picName");
      else
        goodsObj["surfacePic"] = goods.get("picName");
      goodsObj["surfacePicId"] = "";
    } else {
      if (goods.get("surfacePic") != null) {
        var aurl = goods.get("surfacePic")._url;
        if (aurl == undefined)
          aurl = goods.get("surfacePic").get("url");
        goodsObj["surfacePic"] = aurl;
        goodsObj["surfacePicId"] = goods.get("surfacePic").id;
      } else {
        goodsObj["surfacePic"] = "";
        goodsObj["surfacePicId"] = "";
      }
    }
    if (goods.get("title") != null) {
      goodsObj["title"] = goods.get("title");
    } else {
      goodsObj["title"] = "";
    }
    if (goods.get("picWidthxHeight") != null) {
      goodsObj["picWidthxHeight"] = goods.get("picWidthxHeight");
    } else {
      goodsObj["picWidthxHeight"] = "";
    }
    if (goods.createdAt != null) {
      goodsObj["createdTime"] = goods.createdAt.getTime();
    } else {
      goodsObj["createdTime"] = 0;
    }
  }
  return goodsObj;
}

/**
 * 封装商品信息
 */
exports.getGoodsInfo = getGoodsInfo;

function getGoodsInfo(goods) {
  var goodsObj = {};
  if (goods != "" && goods != null && goods != undefined) {
    if (goods.id != null) {
      goodsObj["objectId"] = goods.id;
    } else {
      goodsObj["objectId"] = "";
    }
    if (goods.get("goodNo") != null) {
      goodsObj["goodNo"] = goods.get("goodNo");
    } else {
      goodsObj["goodNo"] = "";
    }
    if (goods.get("collectionNum") != null && goods.get("collectionNum") > 0) {
      goodsObj["collectionNum"] = goods.get("collectionNum");
    } else {
      goodsObj["collectionNum"] = 0;
    }
    if (goods.get("describe") != null) {
      goodsObj["describe"] = goods.get("describe");
    } else {
      goodsObj["describe"] = "";
    }
    if (goods.get("freePost") != null) {
      goodsObj["freePost"] = goods.get("freePost");
    } else {
      goodsObj["freePost"] = "";
    }
    if (goods.get("groupCommission") != null) {
      goodsObj["groupCommission"] = goods.get("groupCommission");
    } else {
      goodsObj["groupCommission"] = 0;
    }
    if (goods.get("originaPrice") != null) {
      goodsObj["originaPrice"] = formatMoneyFixed(goods.get("originaPrice"));
    } else {
      goodsObj["originaPrice"] = "0";
    }
    if (goods.get("price") != null) {
      goodsObj["price"] = formatMoneyFixed(goods.get("price"));
    } else {
      goodsObj["price"] = "0";
    }
    if (goods.get("label") != null) {
      goodsObj["label"] = (goods.get("label"));
    } else {
      goodsObj["label"] = "";
    }
    if (goods.get("discount") != null) {
      goodsObj["discount"] = (goods.get("discount"));
    } else {
      goodsObj["discount"] = 10;
    }
    if (goods.get("originalPrice") != null) {
      goodsObj["originalPrice"] = formatMoneyFixed(goods.get("originalPrice"));
    } else {
      goodsObj["originalPrice"] = formatMoneyFixed(goods.get("price"));
    }
    if (goods.get("promotionPrice") != null) {
      goodsObj["promotionPrice"] = formatMoneyFixed(goods.get("promotionPrice"));
    } else {
      goodsObj["promotionPrice"] = formatMoneyFixed(goods.get("price"));
    }
    if (goods.get("recommend") != null) {
      goodsObj["recommend"] = goods.get("recommend");
    } else {
      goodsObj["recommend"] = "";
    }
    if (goods.get("saleNums") != null) {
      goodsObj["saleNums"] = goods.get("saleNums");
    } else {
      goodsObj["saleNums"] = 0;
    }
    if (goods.get("shopCategory") != null) {
      goodsObj["shopCategory"] = goods.get("shopCategory");
    } else {
      goodsObj["shopCategory"] = "";
    }
    if (goods.get("shopOId") != null) {
      goodsObj["shopOId"] = goods.get("shopOId");
    } else {
      goodsObj["shopOId"] = "";
    }
    if (goods.get("status") != null) {
      goodsObj["status"] = goods.get("status");
    } else {
      goodsObj["status"] = 0;
    }
    if (goods.get("sysCategory") != null) {
      goodsObj["sysCategory"] = goods.get("sysCategory");
    } else {
      goodsObj["sysCategory"] = "";
    }
    if (goods.get("picName") != null && goods.get("picName") != "") {
      if (goods.get("picName").indexOf("http://") == -1)
        goodsObj["surfacePic"] = apis['qiniu']['url'] + "/" + goods.get("picName");
      else
        goodsObj["surfacePic"] = goods.get("picName");
      goodsObj["surfacePicId"] = "";
    } else {
      if (goods.get("surfacePic") != null) {
        var aurl = goods.get("surfacePic")._url;
        if (aurl == undefined)
          aurl = goods.get("surfacePic").get("url");
        goodsObj["surfacePic"] = aurl;
        goodsObj["surfacePicId"] = goods.get("surfacePic").id;
      } else {
        goodsObj["surfacePic"] = "";
        goodsObj["surfacePicId"] = "";
      }
    }
    if (goods.get("title") != null) {
      goodsObj["title"] = goods.get("title");
    } else {
      goodsObj["title"] = "";
    }
    if (goods.get("groupBuying") != null) {
      goodsObj["groupBuying"] = goods.get("groupBuying");
    } else {
      goodsObj["groupBuying"] = 0;
    }
    if (goods.get("groupPrice") != null) {
      goodsObj["groupPrice"] = goods.get("groupPrice");
    } else {
      goodsObj["groupPrice"] = 0;
    }
    if (goods.get("picWidthxHeight") != null) {
      goodsObj["picWidthxHeight"] = goods.get("picWidthxHeight");
    } else {
      goodsObj["picWidthxHeight"] = "";
    }
    if (goods.get("subtitle") != null) {
      goodsObj["subtitle"] = goods.get("subtitle");
    } else {
      goodsObj["subtitle"] = "";
    }
    if (goods.get("stock") != null) {
      goodsObj["stock"] = goods.get("stock");
    } else {
      goodsObj["stock"] = 0;
    }
    if (goods.get("promote") != null) {
      goodsObj["promote"] = goods.get("promote");
    } else {
      goodsObj["promote"] = 0;
    }
    if (goods.get("promotePrice") != null) {
      goodsObj["promotePrice"] = formatMoneyFixed(goods.get("promotePrice"));
    } else {
      goodsObj["promotePrice"] = "0";
    }
  }
  return goodsObj;
}

/**
 * 封装商品图片信息
 */
exports.getGoodsPic = getGoodsPic;

function getGoodsPic(goodsPic) {
  var goodsPicObj = {};
  if (goodsPic != "" && goodsPic != null && goodsPic != undefined) {
    if (goodsPic.id != null) {
      goodsPicObj["objectId"] = goodsPic.id;
    } else {
      goodsPicObj["objectId"] = "";
    }
    if (goodsPic.get("goodsPic") != null && goodsPic.get("goodsPic") != undefined && goodsPic.get("goodsPic") != "") {
      var aurl = goodsPic.get("goodsPic")._url;
      if (aurl == undefined)
        aurl = goodsPic.get("goodsPic").get("url");
      goodsPicObj["goodsPic"] = aurl;
      goodsPicObj["goodsPicId"] = goodsPic.get("goodsPic").id;
    } else {
      if (goodsPic.get("picName") != "" && goodsPic.get("picName") != null && goodsPic.get("picName") != undefined) {
        if (goodsPic.get("picName").indexOf("http://") == -1)
          goodsPicObj["goodsPic"] = apis['qiniu']['url'] + "/" + goodsPic.get("picName");
        else
          goodsPicObj["goodsPic"] = goodsPic.get("picName");
      } else {
        return null;
      }
      goodsPicObj["goodsPicId"] = "";
    }
    if (goodsPic.get("goodsOId") != null) {
      goodsPicObj["goodsOId"] = goodsPic.get("goodsOId");
    } else {
      goodsPicObj["goodsOId"] = "";
    }
    if (goodsPic.get("picWidthxHeight") != null) {
      goodsPicObj["picWidthxHeight"] = goodsPic.get("picWidthxHeight");
    } else {
      goodsPicObj["picWidthxHeight"] = "1x1";
    }
    if (goodsPic.get("picName") != null) {
      goodsPicObj["name"] = goodsPic.get("picName");
    } else {
      goodsPicObj["name"] = "";
    }
    if (goodsPic.get("sortNum") != null) {
      goodsPicObj["sortNum"] = goodsPic.get("sortNum");
    } else {
      goodsPicObj["sortNum"] = 1;
    }
  }
  return goodsPicObj;
}

/**
 * 封装商品规格
 */
exports.getGoodsModel = function (goodsModel) {
  return getGoodsModel(goodsModel);
}

function getGoodsModel(goodsModel) {
  var goodsModelObj = {};
  if (goodsModel != null && goodsModel != "" && goodsModel != undefined) {
    if (goodsModel.id != null) {
      goodsModelObj["objectId"] = goodsModel.id;
    } else {
      goodsModelObj["objectId"] = "";
    }

    if (goodsModel.get("goodsOId") != null) {
      goodsModelObj["goodsOId"] = goodsModel.get("goodsOId");
    } else {
      goodsModelObj["goodsOId"] = "";
    }
    if (goodsModel.get("model") != null && goodsModel.get("model") != "") {
      goodsModelObj["model"] = goodsModel.get("model");
    } else {
      goodsModelObj["model"] = "默认规格";
    }
    if (goodsModel.get("stock") != null) {
      goodsModelObj["stock"] = goodsModel.get("stock");
    } else {
      goodsModelObj["stock"] = "";
    }
  }
  return goodsModelObj;
}

/**
 * 封装商品规格(web)
 */
exports.getWebGoodsModel = getGoodsModel;

function getWebGoodsModel(goodsModel) {
  var goodsModelObj = {};
  if (goodsModel != "" && goodsModel != null && goodsModel != undefined) {
    if (goodsModel.id != null) {
      goodsModelObj["objectId"] = goodsModel.id;
    } else {
      goodsModelObj["objectId"] = "";
    }

    if (goodsModel.get("goodsOId") != null) {
      goodsModelObj["goodsOId"] = goodsModel.get("goodsOId");
    } else {
      goodsModelObj["goodsOId"] = "";
    }
    if (goodsModel.get("model") != null && goodsModel.get("model") != "") {
      goodsModelObj["model"] = goodsModel.get("model");
    } else {
      goodsModelObj["model"] = "默认规格";
    }
    if (goodsModel.get("stock") != null) {
      goodsModelObj["stock"] = goodsModel.get("stock");
    } else {
      goodsModelObj["stock"] = "";
    }
    if (goodsModel.get("numPurchase") != null) {
      goodsModelObj["numPurchase"] = goodsModel.get("numPurchase");
    } else {
      goodsModelObj["numPurchase"] = 0;
    }
    if (goodsModel.get("postage") != null) {
      goodsModelObj["postage"] = goodsModel.get("postage");
    } else {
      goodsModelObj["postage"] = 0;
    }
  }
  return goodsModelObj;
}

/**
 * 封装地址
 */
exports.getReceiveAddress = getReceiveAddress;

function getReceiveAddress(receiveAddress) {
  var receiveAddressObj = {};
  if (receiveAddress != "" && receiveAddress != null && receiveAddress != undefined) {
    if (receiveAddress.id != null) {
      receiveAddressObj["objectId"] = receiveAddress.id;
    } else {
      receiveAddressObj["objectId"] = "";
    }
    if (receiveAddress.get("address") != null) {
      receiveAddressObj["address"] = receiveAddress.get("address");
    } else {
      receiveAddressObj["address"] = "";
    }
    if (receiveAddress.get("isDefault") != null) {
      receiveAddressObj["isDefault"] = receiveAddress.get("isDefault");
    } else {
      receiveAddressObj["isDefault"] = "0";
    }
    if (receiveAddress.get("city") != null) {
      receiveAddressObj["city"] = receiveAddress.get("city");
    } else {
      receiveAddressObj["city"] = "";
    }
    if (receiveAddress.get("tel") != null) {
      receiveAddressObj["tel"] = receiveAddress.get("tel");
    } else {
      receiveAddressObj["tel"] = "";
    }
    if (receiveAddress.get("province") != null) {
      receiveAddressObj["province"] = receiveAddress.get("province");
    } else {
      receiveAddressObj["province"] = "";
    }
    if (receiveAddress.get("name") != null) {
      receiveAddressObj["name"] = receiveAddress.get("name");
    } else {
      receiveAddressObj["name"] = "";
    }
  }

  return receiveAddressObj;
}

/**
 * 封装运费
 */
exports.getFreightInfo = function (freight) {
  return getFreightInfo(freight);
}

function getFreightInfo(freight) {
  var freightObj = {};
  if (freight != "" && freight != null && freight != undefined) {
    if (freight.id != null) {
      freightObj["objectId"] = freight.id;
    } else {
      freightObj["objectId"] = "";
    }
    if (freight.get("area") != null) {
      freightObj["area"] = freight.get("area");
    } else {
      freightObj["area"] = [];
    }
    if (freight.get("goodsNum") != null) {
      freightObj["goodsNum"] = freight.get("goodsNum");
    } else {
      freightObj["goodsNum"] = 0;
    }
    if (freight.get("freight") != null) {
      freightObj["freight"] = freight.get("freight");
    } else {
      freightObj["freight"] = 0;
    }
    if (freight.get("addGoodsNum") != null) {
      freightObj["addGoodsNum"] = freight.get("addGoodsNum");
    } else {
      freightObj["addGoodsNum"] = 0;
    }
    if (freight.get("addFreight") != null) {
      freightObj["addFreight"] = freight.get("addFreight");
    } else {
      freightObj["addFreight"] = 0;
    }
  }
  return freightObj;
}

/**
 * 封装银行卡信息
 */
exports.getAccountBank = getAccountBank;

function getAccountBank(accountBank) {
  var accountBankObj = {};
  if (accountBank != "" && accountBank != null && accountBank != undefined) {
    if (accountBank.id != null) {
      accountBankObj["objectId"] = accountBank.id;
    } else {
      accountBankObj["objectId"] = "";
    }
    if (accountBank.get("name") != null) {
      accountBankObj["name"] = accountBank.get("name");
    } else {
      accountBankObj["name"] = "";
    }
    if (accountBank.get("isDefault") != null) {
      accountBankObj["isDefault"] = accountBank.get("isDefault");
    } else {
      accountBankObj["isDefault"] = "0";
    }
    if (accountBank.get("bankName") != null) {

      accountBankObj["bankName"] = accountBank.get("bankName");
    } else {
      accountBankObj["bankName"] = "";
    }
    if (accountBank.get("bankNo") != null) {
      var bankNo = accountBank.get("bankNo");
      var bankNum = ""
      var len = bankNo.length;
      if ("支付宝" == accountBank.get("bankName")) {
        accountBankObj["isAlipay"] = "1";
//				for(var i=0;i<bankNo.indexOf("@");i++){
//					bankNum=bankNum+"*";
//				}
//				var bankNo=bankNum+accountBank.get("bankNo").substring(bankNo.indexOf("@"));

      } else {
        accountBankObj["isAlipay"] = "0";
//				for(var i=0;i<len-4;i++){
//					bankNum=bankNum+"*";
//				}
//				var bankNo=bankNum+bankNo.substring(len-4);
      }
      accountBankObj["bankNo"] = accountBank.get("bankNo");
    } else {
      accountBankObj["bankNo"] = "";
    }
    if (accountBank.get("icon") != null && accountBank.get("icon") != "") {
      accountBankObj["icon"] = accountBank.get("icon")._url;
      accountBankObj["iconId"] = accountBank.get("icon").id;
    } else {
      accountBankObj["icon"] = "";
      accountBankObj["iconId"] = "";
    }
  }
  return accountBankObj;
}

/**
 * 查询店铺(按销量带分页)
 * @param request 页面请求
 *
 * @param callback
 */


function searchShopUids(uids, skip, cb) {
  var querya = new AV.Query('Shop_account_verify');
  querya.notEqualTo("shopStatus", "1");
  querya.limit(1000);
  querya.skip(skip * 1000);
  querya.find().then(function (vs) {
    if (vs && vs.length > 0) {
      for (var i = 0; i < vs.length; i++) {
        uids.push(vs[i].get("userOId"));
      }
      searchShopUids(uids, skip + 1, cb);
    } else {
      cb();
    }
  });
}


exports.searchShop = function (searchVal, goodType, userOId, page, num, callback) {
  if (page == "" || page == null || page == undefined) {
    page = 1;
  } else {
    page = parseInt(page);
  }
  if (isNaN(page)) {
    page = 1;
  }
  if (searchVal == null || searchVal == undefined)
    searchVal = "";
  searchVal = searchVal.Trim().toLowerCase();


  //var querya = new AV.Query('Shop_account_verify');
  //querya.notEqualTo("shopStatus","1");
  //querya.limit(1000);
  //querya.find().then(function(vs){
  var uIds = [];
  //    if(vs){
  //        for(var i=0;i<vs.length;i++){
  //            uIds.push(vs[i].get("userOId"));
  //        }
  //    }
  searchShopUids(uIds, 0, function () {
    var query = new AV.Query('Shop_shop');
    if (searchVal != "") {
      query.contains("searchVal", searchVal);
    }
    if (goodType != "" && goodType != "all") {
      var numGoodType = parseInt(goodType);
      //小于52是一级类型
      if (numGoodType < 52) {
        query.equalTo("type", goodType.toString())
      } else {
        var queryGoodsType = new AV.Query('Shop_good_type');
        queryGoodsType.equalTo("code", goodType)
        query.matchesKeyInQuery("type", "fatherCode", queryGoodsType);
      }
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.notContainedIn("userOId", uIds);
    query.equalTo("status", "1");
    query.descending("sellNum");
    query.find({
      success: function (shopObj) {
        var shopsInfo = {};
        var jsonShopOId = [];
        var jsonArr = [];
        if (shopObj.length > 0) {
          for (var i = 0; i < shopObj.length; i++) {
            jsonShopOId.push(shopObj[i].id);
            jsonArr.push(getShopInfo(shopObj[i]));
          }
          //查询我是否收藏过这些店铺
          query = new AV.Query('Shop_shop_fav');
          query.containedIn("shopOId", jsonShopOId);
          query.equalTo("userOId", userOId);
          query.find({
            success: function (favObjs) {
              var shopFavMap = {};
              for (var i = 0; i < favObjs.length; i++) {
                shopFavMap[favObjs[i].get("shopOId")] = favObjs[i].id;
              }
              for (var i = 0; i < jsonArr.length; i++) {
                if (shopFavMap[jsonArr[i]["objectId"]] != null) {
                  jsonArr[i]["iscollection"] = "1";
                } else {
                  jsonArr[i]["iscollection"] = "0";
                }
              }
              shopsInfo = jsonArr;
              return callback(null, shopsInfo, page);
            },
            error: function (error) {
              return callback(error.message, null, null);
            }
          });
        } else {
          return callback(null, jsonArr, 1);
        }
      },
      error: function (error) {
        return callback(error.message, null, null);
      }
    });

  })


  //
  //},function(err){
  //
  //    return callback(error.message, null, null);
  //
  //})


}

/**
 * 搜索商品(店铺名字)
 * @param request 页面请求
 *
 * @param callback
 */
exports.searchShopByName = searchShopByName;

/**
 * 查询店铺(店铺名字)
 * @param request 页面请求
 *
 * @param callback
 */
function searchShopByName(searchVal, goodType, address, num, searchObj, callback) {
  var query = new AV.Query('Shop_shop');
  if (searchVal != null && searchVal != "" && searchVal != undefined) {
    searchVal = searchVal.Trim();
    query.contains("name", searchVal);
  }
  if (goodType != null && goodType != "" && goodType != "undefined" && goodType != "all") {
    var numGoodType = parseInt(goodType);
    //小于52是一级类型
    if (numGoodType < 52) {
      query.equalTo("type", goodType)
    } else {
      var queryGoodsType = new AV.Query('Shop_good_type');
      queryGoodsType.equalTo("code", goodType)
      query.matchesKeyInQuery("type", "fatherCode", queryGoodsType);
    }
  }
  if (address != "" && address != null && address != undefined) {
    if (address.indexOf("all") > -1) {
      var queryArea = new AV.Query('Dictionary');
      queryArea.equalTo("name", address.substring(3))
      queryArea.equalTo("type", "1")
      var queryArea1 = new AV.Query('Dictionary');
      queryArea1.matchesKeyInQuery("fatherCode", "code", queryArea);
      query.matchesKeyInQuery("address", "name", queryArea1);
    } else {
      query.equalTo("address", address);
    }
  }
  query.equalTo("status", "1")
  query.limit(num);
  query.descending("saleNums");

  var querya = new AV.Query('Shop_account_verify');
  querya.notEqualTo("shopStatus", "1");
  querya.limit(1000);
  querya.find().then(function (vs) {
    var uIds = [];
    if (vs) {
      for (var i = 0; i < vs.length; i++) {
        uIds.push(vs[i].get("userOId"));


      }
    }
    query.notContainedIn("userOId", uIds);


    query.find({
      success: function (shopObj) {
        var jsonArr = [];
        for (var i = 0; i < shopObj.length; i++) {
          jsonArr.push(getShopInfo(shopObj[i]));
        }
        searchObj["shopsInfo"] = jsonArr;
        return callback(null, searchObj);
      },
      error: function (error) {
        return callback(error.message, null);
      }
    });
  }, function (error) {
    return callback(error.message, null);
  });
}

/**
 * 店铺是否已经收藏
 * @param request
 * @param callback
 */
exports.iscollectionGoods = function (shopOId, userOId, callback) {
  var iscollection = "0";
  if (shopOId == "" || shopOId == null || shopOId == undefined || userOId == "" || userOId == null || userOId == undefined) {
    return callback(iscollection);
  }
  var query = new AV.Query('Shop_shop_fav');
  query.equalTo("shopOId", shopOId);
  query.equalTo("userOId", userOId);
  query.first({
    success: function (favObj) {
      if (favObj != null) {
        iscollection = "1";
      }
      return callback(iscollection);
    },
    error: function (error) {
      return callback("0");
    }
  });
}

exports.formatMoney = formatMoney;

/**
 * 格式化金额，四舍五入到小数第三位（只返回正数）
 * @param money
 */
function formatMoney(money) {
  //return Math.abs(parseFloat(formatMoneyFixed(money)));
  return (parseFloat(formatMoneyFixed(money)));
}

exports.formatMoneyFixed = formatMoneyFixed;

/**
 * 格式化金额，返回带2位小数的字符串，四舍五入到小数第三位（只返回正数）
 * @param money
 */
function formatMoneyFixed(money) {


  if (money == null || money == undefined)
    money = 0;
  money = money.toString();
  if (money.lastIndexOf(".") > -1) {
    if (money.substring(money.lastIndexOf(".") + 3, money.lastIndexOf(".") + 4) == "5") {
      money = (parseFloat(money) + 0.001).toString();
    }
  }
  //money = Math.abs(parseFloat(money)).toFixed(2);
  money = (parseFloat(money)).toFixed(2);
  if (money.indexOf(".") > -1) {
    if (money.substring(money.length - 2) === "00") {
      money = money.substring(0, money.length - 3);
    } else if (money.substring(money.length - 1) === "0") {
      money = money.substring(0, money.length - 1);
    }
  }


  return money;
}

exports.validateParamsEmpty = validateParamsEmpty;//字符非空验证,不能为null和""和undefined
function validateParamsEmpty(params) {
  for (var k in params) {
    if (params[k] == null || params[k] == "" || params[k] == undefined) {
      return k;
    }
  }
  return null;
}

exports.validateNumParamsEmpty = validateNumParamsEmpty;//数字非空验证,不能为null和undefined
function validateNumParamsEmpty(params) {
  for (var k in params) {
    if (params[k] == null || params[k] == undefined) {
      return k;
    }
  }
  return null;
}

exports.sendTextMsg = sendTextMsg;//发送文本消息
function sendTextMsg(formUId, toUId, text, callback) {
  var state = 0;
  var msg = "发送成功";
  var content = {};
  content["content"] = text;
  message.privatePublic(formUId, toUId, "RC:TxtMsg", JSON.stringify(content), "json", function (err, result) {
    if (err) {
      msg = err;
      return callback(state, msg);
    } else {
      state = 1;
      return callback(state, msg);
    }
  })
}

exports.formatContentPic = formatContentPic;

function formatContentPic(content) {
  if (content == null || content == undefined || content == "") {
    return "";
  }
  var tempStr = null;
  var replaceStr = "";
  while (content.indexOf("[") > -1 && content.indexOf("]") > -1) {
    picObj = {};
    tempStr = content.substring(content.indexOf("[") + 1, content.indexOf("]"));
    if (tempStr.split(",").length >= 2) {
      url = tempStr.split(",")[2];
      if (url == undefined)
        url = tempStr.split(",")[1];
      if (url == undefined)
        url = tempStr.split(",")[0];
      replaceStr = "<BR><img src='http://tribemedia.aladada.com/" + url + "?imageMogr2/thumbnail/640x/format/jpg/interlace/1/auto-orient' /><BR>";
    } else {
      replaceStr = "&#91;" + tempStr + "&#93;";
    }
    content = content.replace("[" + tempStr + "]", replaceStr);
  }
  return content;
}

exports.getContentPicUrl = getContentPicUrl;

function getContentPicUrl(content) {
  if (content == null || content == undefined || content == "") {
    return "";
  }
  var url = "";
  var tempStr = null;
  var replaceStr = "";
  if (content.indexOf("[") > -1 && content.indexOf("]") > -1) {
    tempStr = content.substring(content.indexOf("[") + 1, content.indexOf("]"));
    if (tempStr.split(",").length >= 2) {
      url = tempStr.split(",")[2];
      if (url == undefined)
        url = tempStr.split(",")[1];
      if (url == undefined)
        url = tempStr.split(",")[0];
      url = 'http://tribemedia.aladada.com/' + url;
    }
  }
  return url;
}

exports.getIsEnjoy = getIsEnjoy;

/**
 * 是否对帖子点过赞
 * @param threadOId
 * @param userOID
 */
function getIsEnjoy(threadOId, userOId, callback) {
  var enjoyQuery = new AV.Query('Enjoy');
  enjoyQuery.equalTo("threadOId", threadOId);
  enjoyQuery.equalTo("userOId", userOId);
  enjoyQuery.count().then(function (count) {
    var isEnjoy = '0';
    if (count > 0)
      isEnjoy = '1';
    callback(null, isEnjoy);
  }, function (error) {
    callback(error, '0');
  });
}

//获取用户与直播房间的关系
exports.findLiveMember = function (userOId, liveOId, callback) {
  if (!userOId || !liveOId) {
    return callback("错误的参数", null);
  } else {
    var queryFriend = new AV.Query('Live_Member');
    queryFriend.equalTo("userOId", userOId);
    queryFriend.equalTo("liveOId", liveOId);
    queryFriend.include("liveObj");
    queryFriend.first({
      success: function (liveMemberObj) {
        return callback(null, liveMemberObj);
      }, error: function (err) {
        return callback(err.message, null);
      }
    });
  }
}
exports.isAllUpload_Circle = function (circleMsgId, callback) {
  var query = new AV.Query("Circle_msg_source");
  query.equalTo('circleMsgOId', circleMsgId);
  query.find().then(function (sources) {
    var result = [];
    for (var i = 0; i < sources.length; i++) {
      var status = sources[i].get("status");
      if (status == 0) {
        result.push(status);
      }
    }
    if (result.length > 0) {
      return callback(null, false);
    } else {
      return callback(null, true);
    }

  }, function (error) {
    return callback(error, null);
  })
};
exports.getTribeNickName = getTribeNickName;

function getTribeNickName(userId, tribeId, callback) {
  var query = new AV.Query("TribeMember");
  query.equalTo("userOId", userId);
  query.equalTo("tribeOId", tribeId);
  query.first().then(function (tribeMember) {
    if (tribeMember) {
      callback(tribeMember.get("nickName"));
    }
  }, function (error) {
    console.log("getTribeNiceName:" + error);
  })
}

exports.randomString = randomString;

function randomString(len) {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

/**
 * 递归查询    用于查询所有    leancloud  最多一次查询1000
 * @param query
 * @param page
 * @param callback
 * @constructor
 */

exports.recursionQuery = recursionQuery;

function recursionQuery(query, page, callback) {
  query.skip((page - 1) * 100);
  query.find().then(function (result) {
    if (result.length < 100) {
      return callback(true, result);
    } else {
      callback(false, result);
      page++
      recursionQuery(query, page++, callback);
    }

  });
}

exports.postageCompute = postageCompute;

function postageCompute(params, callback) {
  let orderOId = params.orderOId
  let query = new AV.Query('goods_relation_postageModel');
  query.equalTo('orderOId', orderOId)
  query.include('orderObj')
  query.include('shopOrderGoodsObj')
  query.include('postageModelObj')
  query.find().then(async postageModelObjs => {
    console.log('查找订单商品完成')
      // console.log(postageModelObjs)
      var data = []
      for (let i = 0; i < postageModelObjs.length; i++) {
        var postage = 0
        let orderOId = postageModelObjs[i].get("orderOId")
        let postageModelOId = postageModelObjs[i].get("postageModelOId")
        let shopOrderGoodsOId = postageModelObjs[i].get("shopOrderGoodsOId")
        let address = postageModelObjs[i].get("orderObj").get('address') //收货地址
        let goodsName = postageModelObjs[i].get("shopOrderGoodsObj").get('goodsName') //商品名称
        let goodsOId = postageModelObjs[i].get("shopOrderGoodsObj").get('goodsOId') //商品OId
        let notDeliveryRegion = postageModelObjs[i].get("notDeliveryRegion")//不配送区域
        let selfSupportingRegion = postageModelObjs[i].get("selfSupportingRegion")//买家自费区域
        let freeCondition = Number(postageModelObjs[i].get("freeCondition"))//包邮条件0价格1重量/件数
        let conditionValue = Number(postageModelObjs[i].get("conditionValue"))//满多少包邮
        let allFee = Number(postageModelObjs[i].get("shopOrderGoodsObj").get('allFee')) //商品总价
        let num = postageModelObjs[i].get("shopOrderGoodsObj").get('num')//购买数量
        let weight = postageModelObjs[i].get("shopOrderGoodsObj").get('weight')//商品重量
        let isFree = postageModelObjs[i].get("isFree");//是否包邮1包邮0不包
        let billingType = postageModelObjs[i].get("billingType");//计费方式
        let firstWeight = postageModelObjs[i].get("firstWeight");//首重/件
        let firstPostage = postageModelObjs[i].get("firstPostage");//首费
        let moreWeight = postageModelObjs[i].get("moreWeight");//续重/件
        let morePostage = postageModelObjs[i].get("morePostage");//续费
        let isFreeCondition = postageModelObjs[i].get("isFreeCondition");//是否指定包邮条件1指定0未指定
        console.log(
          '订单商品信息：',{
          '收货地址':address,
          '商品总价':allFee,
          '购买数量':num,
          '商品重量':weight,
          '是否包邮1包邮0不包':isFree,
          '计费方式0件数1重量':billingType,
          '首重/件':firstWeight,
          '首费':firstPostage,
          '续重/件':moreWeight,
          '续费':morePostage,
          '是否指定包邮条件1指定0未指定':isFreeCondition,
          '包邮条件0价格1重量/件数':freeCondition,
          '满多少包邮':conditionValue,
        })
        console.log('开始计算邮费')
        if (isFree == 1) { //包邮
          console.log('包邮')
          if (selfSupportingRegion) {
            console.log('有买家自费区域：',selfSupportingRegion)
            let array = selfSupportingRegion.split(",").filter(str => {
              return str.length > 0 && address.indexOf(str) >= 0;
            })
            if (array.length == 0) { //收货地址不是买家自费区域
              console.log('收货地址不是买家自费区域')
              postage = 0
            } else {
              console.log('收货地址是买家自费区域')
              postage = await postageCount(billingType, weight, num, firstWeight, firstPostage, moreWeight, morePostage)
            }
          } else {
            console.log('没有买家自费区域')
            postage = 0
          }
        }
        else {//不包邮
          console.log('不包邮')
          if (isFreeCondition == 1) { //指定包邮条件
            console.log('指定了包邮条件')
            if (freeCondition == 0) { //包邮条件0价格
              console.log('包邮条件0价格')
              if (allFee >= conditionValue) {//商品价格满足包邮条件
                console.log('商品价格满足包邮条件')
                postage = 0
              } else {
                console.log('商品价格不满足包邮条件')
                postage = await postageCount(billingType, weight, num, firstWeight, firstPostage, moreWeight, morePostage)
              }
            } else { //包邮条件1重量/件数
              console.log('包邮条件1重量/件数')
              if (billingType == 0){ //计费方式0件数1重量/件数
                console.log('计费方式0件数')
                if (num >= conditionValue) {//商品件数满足包邮条件
                  console.log('商品件数满足包邮条件')
                  postage = 0
                } else {
                  console.log('商品件数不满足包邮条件')
                  postage = await postageCount(billingType, weight, num, firstWeight, firstPostage, moreWeight, morePostage)
                }
              } else {
                console.log('计费方式1重量')
                if (weight >= conditionValue) {//商品总量数满足包邮条件
                  console.log('商品重量满足包邮条件')
                  postage = 0
                } else {
                  console.log('商品重量不满足包邮条件')
                  postage = await postageCount(billingType, weight, num, firstWeight, firstPostage, moreWeight, morePostage)
                }
              }
            }
          } else {
            console.log('未指定包邮条件')
            postage = await postageCount(billingType, weight, num, firstWeight, firstPostage, moreWeight, morePostage)
          }
        }
        if (notDeliveryRegion) { //存在不配送区域
          console.log('存在不配送区域：',notDeliveryRegion)
          let notRegionTagsArr = notDeliveryRegion.split(',')
          for (let j = 0; j < notRegionTagsArr.length; j++) {
            let notDeliveryRegionIndex = address.indexOf(notRegionTagsArr[j])
            if (notDeliveryRegionIndex != -1) { //收货地址为不配送区域
              console.log('收货地址为不配送区域')
              postage = -1
              break;
            }
          }
          console.log('收货地址不在不配送区域')
        }
        let tempObj = {
          postage,
          goodsName,
          goodsOId,
          orderOId,
          postageModelOId,
          shopOrderGoodsOId,
        }
        data.push(tempObj)
      }
    console.log('检查返回前端数据邮费')
      for (let i = 0; i < data.length; i++) {
        if (data[i].postage == -1) {
          console.log('邮费为-1，收货地址为不配送区域')
          let notDeliveryRegionStr = data[i].goodsName + ',收货地址为不配送区域,请重新调整订单!'
          callback(this.getReturnArr("OK", "10001", notDeliveryRegionStr, ''));
          return
        } else if (data[i].postage == -2) {
          console.log('邮费为-2，未知的计费方式（billingType件数重量）')
          callback(this.getReturnArr("OK", "10001", '未知的计费方式（billingType件数重量）！', ''));
          return
        } else {
          console.log('计算后邮费大于等于0，无异常，继续')
        }
      }
      console.log('邮费计算完成')
      callback(this.getReturnArr("OK", "10000", '邮费计算完成！', data));
    }
  ).catch(error => {
    console.log('postageComputeError:', error)
  })
}
function postageCount(billingType, weight, num, firstWeight, firstPostage, moreWeight, morePostage) {
  var postage = firstPostage
  console.log('默认首件邮费',postage)
  //计费方式0件数1重量
  if (billingType == 0){//计费方式是0件数
    console.log('计费方式是0件数')
    let goodsNum = num
    postage = firstPostage
    if (goodsNum > firstWeight) {
      console.log('商品数量大于首件值')
      postage += Math.ceil((num - firstWeight) / moreWeight) * morePostage
    }
    return postage
  } else if (billingType == 1){//计费方式是1重量
    console.log('计费方式是1重量')
    let goodsWeightCount = num * weight  //订单中该件商品总重量
    console.log('商品总重量：',goodsWeightCount)
    if ((goodsWeightCount-firstWeight) < 0){
      console.log('商品总重量减首重小于0，邮费为首重邮费')
      postage = firstPostage
    } else {
      console.log('商品总重量件首重大于0，邮费需要加续重')
      let moreWeightCount = Math.ceil((goodsWeightCount-firstWeight)/moreWeight)
      console.log('超出首重的份数',moreWeightCount)
      postage += moreWeightCount * morePostage
    }
    return postage
  } else { //未知计费方式
    console.log('未知计费方式')
    return -2
  }
}
